Valid Anagram(leetcode242)

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

//如果是使用map 也是同樣的效果 都是"桶"
public static boolean isAnagram(String s, String t) {
    int[] alphabet = new int[26];
    for (int i = 0; i < s.length(); i++) {
        alphabet[s.charAt(i) - 'a']++;
    }
    for (int i = 0; i < t.length(); i++) {
        alphabet[t.charAt(i) - 'a']--;
    }
    for (int i : alphabet) {
        if (i != 0) {
            return false;
        }
    }
    return true;
}

 

//這是對字符數組 做了一個排序 然後比較
public static boolean isAnagram2(String s, String t) {
    char[] sChar = s.toCharArray();
    char[] tChar = t.toCharArray();

    Arrays.sort(sChar);
    Arrays.sort(tChar);

    return Arrays.equals(sChar, tChar);
}

git:https://github.com/woshiyexinjie/leetcode-xin

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章