标签:style blog io ar os sp java for div
Question:
Write a method to sort an array of strings so that all the anagrams are next to each other.
It‘s similar to Anagrams leetcode Java.
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
For Anagrams leetcode, we use HashMap<sorted String, old String> to store all anagrams.
public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> result = new ArrayList<String>();
if (strs == null || strs.length == 0) {
return result;
}
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for (String str : strs) {
char[] strarray = str.toCharArray();
// inplace sort;
Arrays.sort(strarray);
String temp = strarray.toString();
if (!map.containsKey(temp)) {
ArrayList<String> list = new ArrayList<String>();
list.add(temp);
map.put(temp, list);
}
else {
if (map.get(temp).size() == 1) {
result.add(map.get(temp).get(0));
}
map.get(temp).add(temp);
result.add(temp);
}
}
return result;
}
Can also solve the problem through defining a comparator (self defined comparator in Merge Interval). The idea is from Cracking the code interview.
// note can not sort String directly;
class anagramsComparator implements Comparator(String) {
public String sortString (String s) {
char[] chararray = s.toCharArray();
Arrays.sort(chararray);
return chararray.toString();
}
public int compare(String s1, String s2) {
return sortString(s1).compareTo(sortString(s2));
}
}
public void sortAnagrams(String[] strs) {
Arrays.sort(strs, new anagramsComparator());
}
标签:style blog io ar os sp java for div
原文地址:http://www.cnblogs.com/xiaotra/p/4094609.html