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;
}
本文介绍了如何通过Java代码实现判断两个字符串t和s是否为异位词的算法,重点在于利用字符计数的方法来验证字母是否唯一且数量相同。通过实例和代码展示了如何在O(n)时间内完成字符串比较,适用于面试和技术评估。
284

被折叠的 条评论
为什么被折叠?



