242. 有效的字母异位词

leetcode链接:
https://leetcode.cn/problems/valid-anagram/

方案一

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
class Solution {
public boolean isAnagram(String s, String t) {

HashMap<Character, Integer> hashMap = new HashMap<>();

char[] charArray = s.toCharArray();
for (Character c: charArray) {
System.out.println(c);
if (hashMap.containsKey(c)){
hashMap.replace(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}

char[] charArray1 = t.toCharArray();
for (Character c: charArray1) {
if (hashMap.containsKey(c)){
hashMap.replace(c, hashMap.get(c) - 1);
} else {
return false;
}
}

for (Map.Entry<Character, Integer> map : hashMap.entrySet()) {
if (map.getValue() != 0) {
return false;
}
}
return true;
}
}

结果

解答成功:
执行耗时:145 ms,击败了5.29% 的Java用户
内存消耗:43 MB,击败了5.02% 的Java用户

分析

时间复杂度:
O( n )

空间复杂度:
O( n )

方案二

https://leetcode.cn/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
table[t.charAt(i) - 'a']--;
if (table[t.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

242. 有效的字母异位词
http://yuanql.top/2023/06/12/02_leetcode/242. 有效的字母异位词/
作者
Qingli Yuan
发布于
2023年6月12日
许可协议