LeetCode242-Valid Anagram

题目

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

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?

分析

该题的要求是判断字符串t是否是经过字符串s打乱顺序得到的。也就是说s和t在元素上是严格一样的,只是顺序不同。显然我们可以通过统计字母出现频次解得,先统计s并对频次做加法,后统计t并对频次做减法,当遇到某个元素的频次为0时,证明该元素已经没有可抵消的量了,即两者存在元素不一致。需注意的是一个特殊情况,比如s = ‘ab’,t = ‘a’,则此时也会返回true,为什么?就是因为后者比前者短,所以我们简单起见,在函数一进来就先筛除长度不等的情况。

代码

public class Solution {
    public boolean isAnagram(String s, String t) {
        
        if (s.length() != t.length()) return false;
        
        int[] alphatable = new int[26];
        for (int i = 0; i < s.length(); i++) //统计字符出现个数
            alphatable[s.charAt(i) - 'a']++;
        
        for (int i = 0; i < t.length(); i++) {
            int pos = t.charAt(i) - 'a';
            if (alphatable[pos] == 0) return false;
            else alphatable[pos]--;
        }
        
        return true;
    }
}

Leave a Comment.