LEETCODE--Repeated Substring Pattern

来源:互联网 发布:dos编译级连包java文件 编辑:程序博客网 时间:2024/05/25 21:35

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.

Example 2:
Input: “aba”

Output: False

Example 3:
Input: “abcabcabcabc”

Output: True

Explanation: It’s the substring “abc” four times. (And the substring “abcabc” twice.)

class Solution {public:    bool repeatedSubstringPattern(string str) {        int len = str.size();        int q = 0;        int sublen= 0;        for(int i = 1; i < len; i++){            sublen = i;            if(len % sublen != 0){                continue;            }            if(sublen > len / 2)                return false;            int ipre = i;//The point i may be changed by the while as follow,so we note its pre position;            while(str[q] == str[i]){                q++;                i++;                if( i == len){                    if( ( len - q) == sublen)                        return true;                    else                        return false;                }            }            i = ipre;//Give i its pre value after comparing failure;            q = 0;        }         return false;    }};
0 0
原创粉丝点击