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.

判断两个词是否为异位构词,我们可以借助计数排序算法的思想来解决,代码如下:
public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s == null || t == null) return true;
        int[] result = new int[26];
        for(int i = 0; i < s.length(); i++) {
            result[s.charAt(i) - 'a'] ++;
        }
        for(int i = 0; i < t.length(); i++) {
            result[t.charAt(i) - 'a'] --;
        }
        for(int i = 0; i < result.length; i++) {
            if(result[i] != 0) return false;
        }
        return true;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2278392