242. Valid Anagram

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?

如果是unicode, c - 'a'可能会变成负数,因为减a是为了让小写字母map到从0到25的index上,unicode可以用hashmap来记录

//Time: O(n), Space: O(n)
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {//一定不要忘记开始先比较长度,eg:"ab", "a"
            return false;
        }
        
        int[] map = new int[26];
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map[c - 'a']++;
        }
        
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            map[c - 'a']--;
            
            if (map[c - 'a'] < 0) {
                return false;
            }
        }
        
        return true;
    }

 

posted @ 2018-10-11 15:25  一丝清风一抹红尘  阅读(98)  评论(0编辑  收藏  举报