卖萌的弱渣

I am stupid, I am hungry.

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?

Solution

  • 排序s,t, 看是否相同
(Valid-Anagram.py) download
1
2
3
4
5
6
7
8
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sorted(s) == sorted(t)
  • Java solution: 利用hash_map存每个字母出现次数
(Valid-Anagram.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
    public boolean isAnagram(String s, String t) {
        int[] alpha = new int[26];
        for (int i=0;i<s.length();i++)
            alpha[s.charAt(i)-'a']++;
        for (int i=0;i<t.length();i++)
            alpha[t.charAt(i)-'a']--;

        for (int i=0;i<alpha.length;i++){
            if (alpha[i]!=0)
                return false;
        }
        return true;
    }
}