Anagrams, Leetcode 解题笔记

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

理解题意后第一反应就是用HashMap,这里有个技巧,比较新String时可以先把String排序,这样在与HashMap的key比较更方便。

public class Solution {
    public ArrayList<String> anagrams(String[] strs) {
        HashMap<String, String> map = new HashMap<String, String>();
        ArrayList<String> ret = new ArrayList<String>();
        HashMap<String, Integer> record = new HashMap<String, Integer>();
        for(int i = 0; i < strs.length; i++){
            String str = strs[i];
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String sorted = new String(chars);
            if(!map.containsKey(sorted)){
                map.put(sorted, str);
                record.put(sorted, 0);
            }else{
                if(record.get(sorted) == 0){
                    ret.add(map.get(sorted));
                    ret.add(str);
                    record.put(sorted, 1);
                }else{
                    ret.add(str);
                }
            }
        }
        return ret;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s