[leetcode]459. Repeated Substring Pattern

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.

Example 1:

Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

分析:

给定一个非空字符串,判断其是否是由相同的子字符串组成。如果能由子串组成,说明每个子串的长度<=原字符串长度的一半,可以从原字符串长度的一半遍历到1,如果总长度是当前长度的整数倍m,说明能分成m个子字串,将m个当前子字符串拼接起来与原字符串相比是否相等,相等则返回true; 否则减小子串的长度继续比较,如果遍历到开头,即子串长度为1还不相等的话则返回false。

class Solution {
public:
    bool repeatedSubstringPattern(string s) {
        int len = s.size();
        for(int i = len/2; i >= 1; i--)
        {
            if(len % i == 0)
            {
                int m = len / i;
                string t = "";
                for(int j = 0; j < m; j++)
                     t += s.substr(0, i);
                if(t == s)
                return true;
            }            
        }
        return false;
    }
};

 

你可能感兴趣的:(LeetCode)