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.

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

这道题tag上有hashtable,第一反应用hashmap类,其实这是让用hashtable的思想,比如用int[26] 的数组存s中各个字母出现的次数,然后遍历t 中的各个字母减去对应的int[26]存的次数。代码如下:

public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        int[] charmap = new int[26];
        for (int i = 0; i < s.length(); i++) {
            charmap[s.charAt(i) - 'a'] ++;
            charmap[t.charAt(i) - 'a'] --;
        }
        for (int count:charmap) {
            if(count != 0) {
                return false;
            }
        }
        return true;
    }
}
阅读更多
个人分类: LeetCode Hash Table Sort
上一篇202. Happy Number
下一篇349. Intersection of Two Arrays
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭