Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
给字符串s, t, 判断t 是不是s 的异位词。
也就是判断t 的字母是不是 s中字母的重新排列,每个字母只用一次。
思路:
t 是 s 中字母的重新排列,且每个字母只用一次;就意味着 t 只能用s中的字母,且只能用一次,
那么s和t 的长度一定是相等的,不等的话肯定是false。
不管怎么排列,首先要保证s 和 t 中的每个字母个数得是一致的,个数不一致的话s怎么排列都不会变成 t。
那么只需要统计每个字母出现的个数,然后判断每个字母的个数是否一致即可。
至于具体 s 怎么排列才能得到 t ,本题不关心。
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;
int[] sc = new int[26];
int[] tc = new int[26];
for(int i = 0; i < s.length(); i++) {
sc[s.charAt(i) - 'a'] ++;
tc[t.charAt(i) - 'a'] ++;
}
for(int i = 0; i < 26; i++) {
if(sc[i] != tc[i]) return false;
}
return true;
}