671. 循环单词
The words are same rotate words if rotate the word to the right by loop, and get another. Count how many different rotate word sets in dictionary.
E.g. picture and turepic are same rotate words.
注意事项
所有单词均为小写。
样例
Given dict = ["picture", "turepic", "icturep", "word", "ordw", "lint"]
return 3
.
"picture", "turepic", "icturep"
are same ratote words."word", "ordw"
are same too."lint"
is the third word that different from the previous two words.
这道题我犯得主要错误是string的片段赋值不会;程序不精简时间超限;
class Solution {
/*
* @param words: A list of words
* @return: Return how many different rotate words
*/
int countRotateWords(vector<string> words)
{
// 671. 循环单词 Write your code here
int n=words.size();
if(n==0) return 0;if(n==1) return 1;
vector<int> rept(n,-1);
int result=0;
for(int i=0;i<n;i++)
{
if(rept[i]!=-1||words[i]=="")continue;
else
{
for(int j=i+1;j<n;j++)
{
if(rept[j]!=-1||words[i].length()!=words[j].length()) continue;
int idx=words[i].find(words[j][0]);
if(idx==-1) continue;
string s0="";
while(true)
{
string s1=string(words[i],idx)+string(words[i],0,idx);
if(s1==words[j])
{
rept[i]=i;rept[j]=i;
break;
}
s0=string(words[i],idx+1);
int idx1=s0.find(words[j][0]);
if(idx1==-1) break;
idx=idx1+idx+1; //截取片段查找的结果要加上截取之前的长度
}
}result++;
}
}
return result;
}
};