【LeetCode】242. Valid Anagram 有效的字母异位词(Easy)(JAVA)
题目地址: https://leetcode.com/problems/valid-anagram/
题目描述:
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: 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?
题目大意
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
解题方法
- 因为字符串只包含小写字母,只要把所有的字母出现次数用一个数组存起来即可
- 一个字母的出现此处加起来,一个字母的出现次数减去,最终结果所有字母出现次数为 0 就是字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int[] cou = new int[26];
for (int i = 0; i < s.length(); i++) {
cou[s.charAt(i) - 'a']++;
cou[t.charAt(i) - 'a']--;
}
for (int i = 0; i < cou.length; i++) {
if (cou[i] != 0) return false;
}
return true;
}
}
执行用时:5 ms, 在所有 Java 提交中击败了 48.42% 的用户
内存消耗:38.6 MB, 在所有 Java 提交中击败了 86.53% 的用户