原题网址:https://leetcode.com/problems/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?
思路:变位词的判断通常都是依赖直方图比较,就是以字母作为key,每遇到一个字母,就对该字母的频率计数加1。
public class Solution {
public boolean isAnagram(String s, String t) {
char[] sa = s.toCharArray();
char[] ta = t.toCharArray();
int[] sf = new int[26];
int[] tf = new int[26];
for(int i=0; i<sa.length; i++) sf[sa[i]-'a'] ++;
for(int i=0; i<ta.length; i++) tf[ta[i]-'a'] ++;
for(int i=0; i<26; i++) if (sf[i] != tf[i]) return false;
return true;
}
}