2015年7月1日星期三

lintcode@ 171 Anagrams Java

use isanagram method, same algorithm test if two strings are anagrams, then check whole string list.

public class Solution {
    /**
     * @param strs: A list of strings
     * @return: A list of strings
     */
    public List<String> anagrams(String[] strs) {
        List<String> res= new ArrayList<>();
        if(strs==null)
            return res;
        boolean flag= false;
        HashSet<Integer> tested= new HashSet<>();
        for(int i=0;i<strs.length;i++){
            flag=false;
            for(int j=i+1;j<strs.length;j++){
                if(tested.contains(i))
                    break;
                if(isanagram (strs[i], strs[j]))
                   {
                    res.add(strs[j]);
                    flag=true;
                    tested.add(j);
                   }
                }
            // added anagrams into the return
            if(flag){
                res.add(strs[i]);
            }
        }
        return res;
    }
   
    private boolean isanagram(String s1, String s2){
        if(s1==null || s2== null || s1.length()!=s2.length())
            return false;
        int[] mp= new int[256];
        for(int i=0;i<s1.length();i++){
            mp[s1.charAt(i)]++;
            mp[s2.charAt(i)]--;
        }
        for(int i=0;i<256;i++)
            if(mp[i]!=0)
                return false;
        return true;
    }
}

没有评论:

发表评论