如果一个单词通过循环右移获得的单词,我们称这些单词都为一种循环单词。 现在给出一个单词集合,需要统计这个集合中有多少种不同的循环单词。
例如:picture
和 turepic
就是属于同一种循环单词。
样例
样例 1:
输入 : dict = ["picture", "turepic", "icturep", "word", "ordw", "lint"]
输出 : 3
说明 :
"picture", "turepic", "icturep" 是相同的旋转单词。
"word", "ordw" 也相同。
"lint" 是第三个不同于前两个的单词。
注意事项
所有单词均为小写。
解题思路1:
一开始的想法是把所有可能的翻转字符全部存入Set中,然后再遍历dict,如果set中不存在则结果加一,最后输出结果即可。但是这样空间复杂度太高了。
public class Solution {
/*
* @param words: A list of words
* @return: Return how many different rotate words
*/
public int countRotateWords(List<String> words) {
// Write your code here
if(words == null || words.size() == 0)
return 0;
HashSet<String> set = new HashSet<>();
int res = 0;
for(String word : words){
if(!set.contains(word)){
set.addAll(totalRotateWords(word));
res++;
}
}
return res;
}
//输出word所有可能的翻转字符
private List<String> totalRotateWords(String word){
List<String> res = new ArrayList<>();
for(int i=0; i<word.length(); i++){
res.add(rotateWord(word,i));
}
return res;
}
//根据n位置,翻转word
private String rotateWord(String word, int n){
StringBuilder s = new StringBuilder(word);
StringBuilder ss = s.reverse();
StringBuilder temp1 = new StringBuilder(ss.substring(0,n+1));
StringBuilder ssL = temp1.reverse();
StringBuilder temp2 = new StringBuilder(ss.substring(n+1));
StringBuilder ssR = temp2.reverse();
StringBuilder res = new StringBuilder();
res.append(ssL);
res.append(ssR);
return res.toString();
}
}
二刷
public class Solution {
/*
* @param words: A list of words
* @return: Return how many different rotate words
*/
public int countRotateWords(List<String> words) {
// Write your code here
Set<String> set = new HashSet<>();
int res = 0;
for(String str : words){
if(!set.contains(str)){
res++;
String s = str + str;
for(int i=0; i<str.length(); i++)
set.add(s.substring(i, i+str.length()));
}
}
return res;
}
}
解题思路2:
为了降低空间复杂度,建立set后边添加边移除,思路是遍历words,对于每一个word先在set中删除所有关于此word的所有翻转字符,然后再添加一个,这样如果遍历到相同字符得来的翻转字符则总会只添加一个。
其中求word所有的翻转字符,有一个简单的方法:可以先将w变成w+w,然后求新字符串的substring。这样不需要考虑前后拼接问题,代码更简练。
public class Solution {
/*
* @param words: A list of words
* @return: Return how many different rotate words
*/
public int countRotateWords(List<String> words) {
// Write your code here
Set<String> set = new HashSet<String>();
for (String w : words) {
String s = w + w;
//移除set中关于w所有的翻转字符
for (int i = 0; i < w.length(); i++)
set.remove(s.substring(i, i + w.length()));
set.add(w);
}
return set.size();
}
}