Question:
An anagram is a word that can be written as a permutation of the characters of another word, like "dirty room" and "dormitory"(ignore spaces). However, "the" and "thee" are not anagrams, since "the" only has a single "e" whereas "thee" has two "e" characters (spaces can occur zero, or multiple times, however).
Give a list of words as input, you should output another list of strings, each containing words that are mutual anagrams.
Each string of the output should be a single group of anagrams joined with commas.
Within an output string, the expressions should be sorted lexicographically. If a group contains only a single element, output that one-element group as a single string. And the strings should also be output in lexicographical order.
Given e.g.:
- pear
- amleth
- dormitory
- tinsel
- dirty room
- hamlet
- listen
- silent
The output would be:
amleth,hamlet dirty room,dormitory listen,silent,tinsel pear
My solution is:
- Convert into each string to a
char
array, and in the meantime, compare to eachchar
array group. After that, get how many groups for an input string array, and divide them into a respective group. - Sort each group alphabetically, and eventually order by group.
Time-complexity is \$O(n^2)\$
I wrote code for this question, and it has a poor time-complexity. Are there any suggestions for this?
ArrayList<char[]> group = new ArrayList<char[]>();
ArrayList<ArrayList<String>> originalList = new ArrayList<ArrayList<String>>();
String[] tempstr = str.clone(); //clone could do deep copy, and avoid to change str.
//Category group for str.
outerloop:
for(int pos=0; pos<tempstr.length; pos++){
tempstr[pos]= tempstr[pos].trim().replaceAll(" ", "");
char[] c = new char[tempstr[pos].length()];
tempstr[pos].getChars(0,tempstr[pos].length(),c,0); //last character is at index srcEnd-1
Arrays.sort(c);//ignore character's order in string.
ArrayList<String> sArrList = new ArrayList<String>();
Iterator<char[]> it = group.iterator();
while(it.hasNext()){
sArrList.clear();
char[] comparedChars = (char[])it.next();
if(Arrays.equals(comparedChars,c)){//only compare character in same index.
sArrList = originalList.get(group.indexOf(comparedChars));
sArrList.add(str[pos]);
continue outerloop;
}
}
// can not find group
sArrList.add(str[pos]);
originalList.add(sArrList);
group.add(c);
}
//Following begin to do sorting.
String[] groupStr = new String[group.size()];
Iterator<ArrayList<String>> it2 = originalList.iterator();
for(int groupId=0 ; groupId<group.size() && it2.hasNext(); groupId++){
ArrayList<String> temp = it2.next();
Collections.sort(temp); // let string in each single row sort by alphabet.
for(Iterator it3 = temp.iterator();it3.hasNext();){
String ss = (String) it3.next();
if(groupStr[groupId]==null || groupStr[groupId].length()==0) groupStr[groupId] = ss;
else groupStr[groupId] += "," + ss;
}
}