首页 > 代码库 > 9.2
9.2
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());
}
9.2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。