[leetcode]459. Repeated Substring Pattern

[leetcode]459. Repeated Substring Pattern


Analysis

待会要考政治—— [生死有命富贵在天!!!]

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
判断给定的字符串是否是由子字符串重复组成的。首先看字符串长度len是否是偶数,如果不是直接pass,然后再把字符串分成2份,3份,…看这些分段后的子字符串是否相同。

Implement

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int len = s.length();
        bool match;
        for(int i=2; i<=len; i++){
            if(len % i == 0){
                int cnt = len/i;
                int j;
                for(j=0; j<i-1; j++){
                    string t1 = s.substr(j*cnt, cnt);
                    string t2 = s.substr((j+1)*cnt, cnt);
                    if(t1 != t2)
                        break;
                }
                if(j == i-1)
                    return true;
            }
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80820925
今日推荐