【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.

 

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.)

题意:

查看一个字符串是否可以由子字符串重复组成,可以的话返回真,否则返回假

思路:

改变扫描步长,二重循环

1.假定长度为p的字符串可以重复组成,1=<p<=len(s)

2.重复多次循环,每个循环中不断验证str[i]!=str[i+p],如果为真,break;

3.如果有一次可以扫描到结尾,也就是i+p=l,而且i%p==0,那么返回真

 1 bool repeatedSubstringPattern(char* str) {
 2     int p,i;
 3     int l=strlen(str);
 4     int flag=0;
 5     for(p=1;p<=l/2;p++)
 6     {
 7         for(i=0;i<l-p;i++)
 8         {
 9             flag=0;
10             if(str[i]!=str[i+p])
11                 {
12                     flag=1;
13                     break;
14                 }
15         }
16         if(0==flag&&i%p==0)
17             return true;
18     }
19     return false;
20 }

这种解法的时间复杂度为O(n^2),还有一种利用KMP算法的,时间复杂度为O(n),我还没做,待补充

posted @ 2016-12-10 23:22  wilderness  阅读(185)  评论(0编辑  收藏  举报