a solution using primes factorization


  • 0
    L
    class Solution {
    public:
        bool repeatedSubstringPattern(string s) {
            unordered_set<int> factors;
            int i = 2;
            int len = s.size();
            if (len == 1)
                return false;
            int n = len;
    // prime factorization
            while (i * i <= n) {
                if (n % i == 0) {
                    factors.insert(i);
                    n = n/i;
                } else {
                    i++;
                }
            }
            factors.insert(n);
    // check each prime
            for (auto it = factors.begin(); it != factors.end(); ++it) {
                int size = len/(*it);
                for (int i=0; i<size; ++i)
                    for (int j=1; i+j*size < len; ++j)
                        if (s[i] != s[i+j*size])
                            goto False;
                return true;
                False: ;
            }
            return false;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.