leetcode做题总结,题目Anagrams 2012/03/19

来源:互联网 发布:linux svn ignore 编辑:程序博客网 时间:2024/05/21 21:47

这道题是https://oj.leetcode.com/problems/anagrams/

题目有点不太清晰,意思是说把有异构的字符串进行归类,然后按照类别依次输出,只有超过两个字符串异构才进行输出。我学到的有把一个String转成char array可以用toCharArray(),但是要注意如果String是“”返回的Array也是空的。还有就是存在容器里的list,array对其进行修改之后都是不用打回容器里的。


public class Solution {    public List<String> anagrams(String[] strs) {        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();        ArrayList<String> res = new ArrayList<String>();        if(strs.length==0)            return res;        for(int i=0;i<strs.length;i++){            char[] store = strs[i].toCharArray();            Arrays.sort(store);            String sortstr = new String(store);//cannot use toString() here            if(strs[i].equals(""))                sortstr="";            if(map.containsKey(sortstr)){                map.get(sortstr).add(strs[i]);//unnecessary to put it back since it is a list.            }else{                ArrayList<String> l = new ArrayList<String>();                l.add(strs[i]);                map.put(sortstr,l);            }        }        //        Iterator<ArrayList<String>> iter = map.values().iterator();        while(iter.hasNext()){            ArrayList<String> tmp = iter.next();            if(tmp.size()>1)                res.addAll(tmp);        }        return res;    }}

Update 2015/08/31: 分享一个九章的解法,使用数组记录有哪些字母然后求hash,其他思路一样

public class Solution {    /**     * @param strs: A list of strings     * @return: A list of strings     */    private int getHash(int[] count) {        int hash = 0;        int a = 378551;        int b = 63689;        for (int num : count) {            hash = hash * a + num;            a = a * b;        }        return hash;    }         public List<String> anagrams(String[] strs) {        // write your code here        ArrayList<String> result = new ArrayList<String>();        HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();        for (String str : strs) {            int[] count = new int[26];            for (int i = 0; i < str.length(); i++) {                count[str.charAt(i) - 'a']++;            }            int hash = getHash(count);            if (!map.containsKey(hash)) {                map.put(hash, new ArrayList<String>());            }            map.get(hash).add(str);        }        for (ArrayList<String> tmp : map.values()) {            if (tmp.size() > 1) {                result.addAll(tmp);            }        }        return result;    }}


0 0
原创粉丝点击