[leetcode] 459. Repeated Substring Pattern

来源:互联网 发布:软件开发学校好吗 编辑:程序博客网 时间:2024/06/08 15:55

Qustion:

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: TrueExplanation: It's the substring "ab" twice.
Example 2:Input: "aba"Output: False
Example 3:Input: "abcabcabcabc"Output: TrueExplanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)

Solution:

先想着把整个字符串分成两部分(如果可以的话),看这两部分是否相等;若否,则再分成三部分(如果可以),看这三部分是否相等;如此类推,一直到分成s.size()部分,每部分一个字符,看是否相等;若不等,则返回false。
helper函数用于判断多个部分是否相等,逐个字符逐个字符判断。

class Solution {public:    bool repeatedSubstringPattern(string s) {        for (int i = 2; i <= s.size(); i++) {            if (s.size() % i == 0 && helper(s, s.size()/i))                return true;        }        return false;    }    bool helper(string & s, int k) {        int i = k, j = 0;        while (i < s.size()) {            if (s[i++] != s[j++])                return false;            if (j == k)                j = 0;        }        return true;    }};