




Sponsored
Sponsored
One approach is to take a substring of the given string and repeatedly concatenate to check if it forms the original string. This involves iterating through possible substring lengths and using modular arithmetic to assess potential repeats.
Time Complexity: O(n^2). Space Complexity: O(n).
1class Solution {
2    public boolean repeatedSubstringPattern(String s) {
3        int n = s.length();
4        for (int i = 1; i <= n / 2; i++) {
5            if (n % i == 0) {
6                StringBuilder sb = new StringBuilder();
7                String part = s.substring(0, i);
8                for (int j = 0; j < n / i; j++) {
9                    sb.append(part);
10                }
11                if (sb.toString().equals(s)) {
12                    return true;
13                }
14            }
15        }
16        return false;
17    }
18}The Java solution takes advantage of the StringBuilder for efficient string concatenation and equality checks.
Another approach is using the property of doubled strings. By creating a new string by repeating the original and removing the first and last character, we can check if the original string exists within this new string.
Time Complexity: O(n). Space Complexity: O(n).
1#include<string>
using namespace std;
class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        string ss = s + s;
        return ss.substr(1, ss.size() - 2).find(s) != string::npos;
    }
};C++ solution utilizes substring and find standard library functions on the concatenated string derived from repeating the string, checking existence.