Leetcode 459. Repeated Substring Pattern
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You need to return true if s can be constructed from a substring, otherwise return false.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times.
s will be between 1 and 10^4.s consists of lowercase English letters only.The problem can be solved by utilizing a string manipulation trick:
s is composed of repeating a substring, doubling s and then removing the first and the last character will still contain s somewhere in the middle.class Solution {
public boolean repeatedSubstringPattern(String s) {
String doubled = s + s;
String modified = doubled.substring(1, doubled.length() - 1);
return modified.contains(s);
}
}
n is the length of the string s.
s with itself to get doubled = s + s.doubled to form modified.s is present in modified, then s can be formed by repeating some substring. Hence, return true.false.This approach leverages string manipulation to efficiently determine if a string has a repeated substring pattern.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?