码迷,mamicode.com
首页 > 其他好文 > 详细

9.2

时间:2014-11-13 14:27:13      阅读:206      评论:0      收藏:0      [点我收藏+]

标签: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());
}

 

9.2

标签:style   blog   io   ar   os   sp   java   for   div   

原文地址:http://www.cnblogs.com/xiaotra/p/4094609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!