leetcode 49. Group Anagrams

来源:互联网 发布:扫描服务器开放的端口 编辑:程序博客网 时间:2024/05/22 12:00

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:

[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
Note: All inputs will be in lower-case.

第一个想法:List<HashMap<Character,Integer>>每个单词进来之后 逐个去判断符不符合?好像效率不高 主要是这个list遍历的效率不够好先试试:    list:        {"a":1,"b":1,"c":2,"d":3}        {"e":1,"g":2,"h":1,"j":2}    对于进来的单词也做个hashmap:        {"e":1,"g":2,"h":1}    匹配的时候要完全一致才行 所以length不等:pass    逐个keyvalue比较 不等:pass    遍历一遍都没有相等的 加入list

后面怎么把这个str 和这个hashmap联系起来。。也是挺费劲的。。。
看了看网上的博客:
发现真是amazing 我个猪
为什么要用hashmap存template?
直接排序后的字符串本身不就可以了 关键是这样比较template时就直接字符串比较就可以了!

templates:HashMap<String:String[]>所有字符串排序 然后生成这个hashmap就可以了
public List<List<String>> groupAnagrams(String[] strs) {        List<List<String>> result = new ArrayList<List<String>>();        HashMap<String,List<String>> templates = new HashMap<String,List<String>>();        for(String str:strs){            char[] chars = str.toCharArray();            Arrays.sort(chars);            //String template = chars.toString();             String template = new String(chars);            //System.out.println(template);            if(templates.containsKey(template)){                templates.get(template).add(str);            }            else{                List<String> t = new ArrayList<String>();                t.add(str);                templates.put(template, t);            }        }        for(List<String> t:templates.values()) result.add(t);        return result;    }

重要!!!!!!!!!!!!:
String template = chars.toString(); 不行
String template = new String(chars);可行
看一下这里的区别:
char[] 的toString()方法:
Returns a string representation of the object. In general, the toString method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + ‘@’ + Integer.toHexString(hashCode())
Returns:a string representation of the object.
char[] 是一个数组 数组是一个对象 数组并没有重写toString方法
好比int[] 调用toString()方法 你不能期望返回一个“[1,2,3]”字符串吧
甚至于person[]调用toString()方法 你不能期望返回一个 “{wanglei:23,yanximin:23}”的字符串吧
所以char[]也会返回一个“[C@70dea4e”的无意义字符串
如果希望通过char[] chars = [“a”,”b”,”c”]得到一个“abc”字符串 应该用new String(chars)这样啊 基础不牢固误区有很多啊。。。。

0 0