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

[lintcode medium]Anagrams

时间:2015-12-19 06:36:34      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Anagrams

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

Example

Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].

Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].

Note

All inputs will be in lower-case

 

 

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        // write your code here
        
        List<String> list=new ArrayList<String>();
        if(strs==null ||strs.length==0) return list;
        HashMap<String,Integer> visited=new HashMap<String,Integer>();
        for(int i=0;i<strs.length;i++)
        {
            char[] ch=strs[i].toCharArray();
            Arrays.sort(ch);
            String s=new String(ch);
            
            if(visited.containsKey(s))
            {
                int index=visited.get(s);
                if(index!=-1)
                {
                    list.add(strs[index]);
                    visited.put(s,-1);
                }
                list.add(strs[i]);
            }
            else
            {
                visited.put(s,i);
            }
        }
        return list;
    }
}

 

[lintcode medium]Anagrams

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5058579.html

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