1. 程式人生 > >[Amazon] Two Strings Are Anagrams (Compare Strings)

[Amazon] Two Strings Are Anagrams (Compare Strings)

Write a method anagram(s,t) to decide if two strings are anagrams or not.

What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.

Example

Given s = "abcd", t = "dcab", return true.
Given s = "ab", t = "ab", return true.
Given s = "ab", t = "ac"

, return false.

Challenge 

O(n) time, O(1) extra space

思路:兩串字串分別統計每個出現字元的個數,如果有個數不等的,就不是anagram,反之

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        Map<Character,Integer> mapS=new HashMap<>();
        Map<Character,Integer> mapT=new HashMap<>();
        
        for(int i=0;i<s.length();i++){
            char ch=s.charAt(i);
            if(!mapS.containsKey(ch)){
                mapS.put(ch,1);
            }else{
                mapS.put(ch,mapS.get(ch)+1);
            }
        }
        for(int i=0;i<t.length();i++){
            char ch=t.charAt(i);
            if(!mapT.containsKey(ch)){
                mapT.put(ch,1);
            }else{
                mapT.put(ch,mapT.get(ch)+1);
            }
        }
        
        for(int i=0;i<s.length();i++){
            char ch=t.charAt(i);
            if(mapS.get(ch)!=mapT.get(ch)){
                return false;
            }
        }
        
        return true;
    }
}

方法二:統計一個字串裡每個字元出現的個數,在統計另一個字串字元的時候,個數- -,如果哪個字元的的總數不為0就false,反之。

public class Solution {
    /**
     * @param s: The first string
     * @param b: The second string
     * @return true or false
     */
    public boolean anagram(String s, String t) {
        if(s.length()!=t.length()){
            return false;
        }
        
        int[] count=new int[256];
        for(int i=0;i<s.length();i++){
            count[s.charAt(i)]++;
        }
        for(int i=0;i<t.length();i++){
            count[t.charAt(i)]--;
        }
        
        for(int i=0;i<count.length;i++){
            if(count[i]!=0){
                return false;
            }
        }
        return true;
    }
}

思路程式碼一樣的55. Compare Strings :點選開啟連結

public class Solution {
    /**
     * @param A : A string includes Upper Case letters
     * @param B : A string includes Upper Case letter
     * @return :  if string A contains all of the characters in B return true else return false
     */
    public boolean compareStrings(String A, String B) {
        int[] count=new int[26];
       
        for(int i=0;i<A.length();i++){
            count[A.charAt(i)-'A']++;
        }
        
        for(int i=0;i<B.length();i++){
            count[B.charAt(i)-'A']--;
        }
        
        for(int i=0;i<count.length;i++){
            if(count[i]<0){
                return false;
            }
        }
        return true;
    }
}