1.问题描述
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.)
来自 https://leetcode.com/problems/repeated-substring-pattern/description/
2.题目分析
给定一个非空字符串,检测这个字符串是否可以由它的一个子串通过拼接构造出来,即判断字符串的周期性。通过find函数找出第一个和和s[0]相同的位置,假设这个位置gap是周期,再通过isminsubstr函数判断字符串是否是这个周期的,若函数返回true,则结束,返回true,否者再通过find寻找下一个可能的周期。其中isminsubstr函数用于判断字符串是否具有周期gap,判断的方法是首先这个字符串长度必须是gap的整数倍,其次,各个位置的字符必须周期重复。
3.C++代码
//我的代码:(beats 39%)
bool isminsubstr(string s, int gap)//判断s是否具有周期gap
{
int L = s.length();
if(L%gap != 0)//长度不是gap的整数倍
return false;
for(int start=0;start<gap;start++)
for (int i = start+gap; i < L; i=i+gap)
{
if (s[start] != s[i])//不满足周期重复
return false;
}
return true;
}
bool repeatedSubstringPattern(string s)
{
int L = s.length();
int gap = s.find(s[0],1);//假设的最小周期
if (gap == -1)
return false;
while (gap < L&&gap!=-1)
{
if (isminsubstr(s, gap))
return true;
else
gap= s.find(s[0], gap+1);//寻找下一个周期
}
return false;
}
//别人家的代码
bool repeatedSubstringPattern2(string str)
{
int i = 1, j = 0, n = str.size();
vector<int> dp(n+1,0);
while (i < str.size())
{
if (str[i] == str[j])
dp[++i] = ++j;
else if (j == 0)
++i;
else
j = dp[j];
}
return dp[n] && ((dp[n] % (n - dp[n])) == 0);
}
//基本思路
4.string类的compare函数
在C++中使用std::string编写字符串相关操作时,经常使用find方法,但在有些场景下需要判断字符串是否相同,因而需要使用compare方法。下面是用法测试:
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
string str1("abc");
string str2("abcabcabc");
if (str1.compare("abc") == 0)
cout << str1 << " is abc!" << endl;
if (str1.compare(str2) != 0)
cout << str1 << " is not " << str2 << endl;
if (str2.compare(6, 3, "abc") == 0)
cout << str2 << " 'index from 6 about 3char is abc!" << endl;
if (str2.compare(0,3, str1) == 0)
cout << str2 << " 'index from 0 about 3char is equal str1!" << endl;
if (str2.compare(6, 3, str1, 0, 3) == 0)
cout << str2 << " 'index from 6 about 3char is equal str1'index from 0 about 3char!" << endl;
return 0;
}