-
Notifications
You must be signed in to change notification settings - Fork 1
/
Question032.java
55 lines (50 loc) · 1.6 KB
/
Question032.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.hncboy.swordreferstoofferspecial;
/**
* @author hncboy
* @date 2021/10/30 11:27
* @description 剑指 Offer II 032.有效的变位词
*
* 给定两个字符串 s 和 t ,编写一个函数来判断它们是不是一组变位词(字母异位词)。
* 注意:若 s 和 t 中每个字符出现的次数都相同且字符顺序不完全相同,则称 s 和 t 互为变位词(字母异位词)。
*
* 示例 1:
* 输入: s = "anagram", t = "nagaram"
* 输出: true
*
* 示例 2:
* 输入: s = "rat", t = "car"
* 输出: false
*
* 示例 3:
* 输入: s = "a", t = "a"
* 输出: false
*
* 提示:
* 1 <= s.length, t.length <= 5 * 104
* s and t 仅包含小写字母
*
* 进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
* 注意:本题与主站 242 题 {@link com.hncboy.ValidAnagram}
* 相似(字母异位词定义不同):https://leetcode-cn.com/problems/valid-anagram/
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/dKk3P7
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class Question032 {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length() || s.equals(t)) {
return false;
}
int[] hash = new int [26];
for (char ch : s.toCharArray()) {
hash[ch - 'a']++;
}
for (char ch : t.toCharArray()) {
if (--hash[ch - 'a'] < 0) {
return false;
}
}
return true;
}
}