Sunday, January 24, 2016

242 Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.

Naive solution:
public class Solution {
    public boolean isAnagram(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        if(slen != tlen){
            return false;
        } else {
            int round = slen;
            int cnt = slen;
// Use a ArrayList to store the characters, easy to add and remove, resize automaticly
            ArrayList<Character> s_array = new ArrayList<Character>(slen);
            ArrayList<Character> t_array = new ArrayList<Character>(slen);
            for(int i = 0; i < slen; i++){
                s_array.add(s.charAt(i));
            }
            for(int i = 0; i < slen; i++){
                t_array.add(t.charAt(i));
            }
            /*
            This is a way to convert String to seperate chars
            char s_char = new char[slen];
            char t_char = new char[tlen];
            s.getChars(0, slen, s_char, 0);
            t.getChars(0, tlen, t_char, 0); */
            while(round > 0){
                round--;
                for(int j = 0; j < cnt; j++){
                    if(s_array.get(round) == t_array.get(j)){
                        cnt--;
                        t_array.remove(j);
                        break;//stucked here for 4 hours. At first I use a 'continue' which did not stop the loop and 
// it keep remove t_array untill remove all the items.
                    }
                }
            }
            if(t_array.isEmpty()){
                return true;
            } else {
                return false;
            }
        }        
    }
}

//a better solution
//just compare the value of two strings

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        int[] count = new int[26];
        for(int i=0;i<s.length();i++){
            count[s.charAt(i)-'a']++;
            count[t.charAt(i)-'a']--;
        }
        for(int i:count){
            if(i!=0){
                return false;
            }
        }
        return true;
    }
}


No comments:

Post a Comment