1. 程式人生 > >Two Strings Are Anagrams

Two Strings Are Anagrams

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

判斷兩個字串包含的字母知否一致,也就是是否能夠通過改變字母的順序變成相同的字串。

如果一致,則返回true,如果不一致,返回false。

Clarification

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.


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[(int) s.charAt(i)]++;
        }
        
        for(int j = 0; j < t.length(); j++) {
            count[(int) t.charAt(j)]--;
            if (count[(int) t.charAt(j)] < 0){
                return false;
            }
        }
        return true;
    }
};