LintCode-乱序字符串

时间:2022-06-09 09:09:05

题目描述:

  给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。

注意事项

  所有的字符串都只包含小写字母

样例

  对于字符串数组 ["lint","intl","inlt","code"]

  返回 ["lint","inlt","intl"]

 public class Solution {
/**
* @param strs: A list of strings
* @return: A list of strings
*/ public static boolean anagram(String s, String t) {
if(s.length() != t.length())
return false;
else{
for(int i=0;i<t.length();i++){
if(s.indexOf(t.charAt(i))!=-1){
int j = s.indexOf(t.charAt(i));
s = s.substring(0, j)+s.substring(j+1);
}
else{
return false;
}
}
return true;
}
} public List<String> anagrams(String[] strs) {
// write your code here
List<String> rStr = new LinkedList<String>();
int length = strs.length;
for(int i=0;i<length;++i){
String str = strs[i];
if(str!=null){
for(int j=i+1;j<length;j++){
String strToCom = strs[j];
if(strToCom != null){
if(anagram(str,strToCom)){
if(strs[i]!=null){
rStr.add(str);
}
if(strs[j]!=null){
rStr.add(strToCom);
} strs[i] = null;
strs[j] = null;
}
} }
} }
return rStr; }
}