Skip to content

Commit e406010

Browse files
committed
feat: add solutions to lc problem: No.0242
No.0242.Valid Anagram
1 parent 12f0d6f commit e406010

File tree

9 files changed

+167
-129
lines changed

9 files changed

+167
-129
lines changed

solution/0200-0299/0242.Valid Anagram/README.md

+59-46
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,13 @@
4242

4343
<!-- 这里可写通用的实现逻辑 -->
4444

45-
数组或哈希表累加 s 中每个字符出现的次数,再减去 t 中对应的每个字符出现的次数。遍历结束后,若字符中出现次数不为 0 的情况,返回 false,否则返回 true。
45+
**方法一:计数**
46+
47+
我们先判断两个字符串的长度是否相等,如果不相等,说明两个字符串中的字符肯定不同,返回 `false`
48+
49+
否则,我们用哈希表或者一个长度为 $26$ 的数组来记录字符串 $s$ 中每个字符出现的次数,然后遍历另一个字符串 $t$,每遍历到一个字符,就将哈希表中对应的字符次数减一,如果减一后的次数小于 $0$,说明该字符在两个字符串中出现的次数不同,返回 `false`。如果遍历完两个字符串后,哈希表中的所有字符次数都为 $0$,说明两个字符串中的字符出现次数相同,返回 `true`
50+
51+
时间复杂度 $O(n)$,空间复杂度 $O(C)$,其中 $n$ 是字符串的长度;而 $C$ 是字符集的大小,本题中 $C=26$。
4652

4753
<!-- tabs:start -->
4854

@@ -55,11 +61,12 @@ class Solution:
5561
def isAnagram(self, s: str, t: str) -> bool:
5662
if len(s) != len(t):
5763
return False
58-
chars = [0] * 26
59-
for i in range(len(s)):
60-
chars[ord(s[i]) - ord('a')] += 1
61-
chars[ord(t[i]) - ord('a')] -= 1
62-
return all(c == 0 for c in chars)
64+
cnt = Counter(s)
65+
for c in t:
66+
cnt[c] -= 1
67+
if cnt[c] < 0:
68+
return False
69+
return True
6370
```
6471

6572
### **Java**
@@ -72,13 +79,13 @@ class Solution {
7279
if (s.length() != t.length()) {
7380
return false;
7481
}
75-
int[] chars = new int[26];
82+
int[] cnt = new int[26];
7683
for (int i = 0; i < s.length(); ++i) {
77-
++chars[s.charAt(i) - 'a'];
78-
--chars[t.charAt(i) - 'a'];
84+
++cnt[s.charAt(i) - 'a'];
85+
--cnt[t.charAt(i) - 'a'];
7986
}
80-
for (int c : chars) {
81-
if (c != 0) {
87+
for (int i = 0; i < 26; ++i) {
88+
if (cnt[i] != 0) {
8289
return false;
8390
}
8491
}
@@ -93,18 +100,15 @@ class Solution {
93100
class Solution {
94101
public:
95102
bool isAnagram(string s, string t) {
96-
if (s.size() != t.size())
103+
if (s.size() != t.size()) {
97104
return false;
98-
vector<int> chars(26, 0);
99-
for (int i = 0, n = s.size(); i < n; ++i) {
100-
++chars[s[i] - 'a'];
101-
--chars[t[i] - 'a'];
102105
}
103-
for (int c : chars) {
104-
if (c != 0)
105-
return false;
106+
vector<int> cnt(26);
107+
for (int i = 0; i < s.size(); ++i) {
108+
++cnt[s[i] - 'a'];
109+
--cnt[t[i] - 'a'];
106110
}
107-
return true;
111+
return all_of(cnt.begin(), cnt.end(), [](int x) { return x == 0; });
108112
}
109113
};
110114
```
@@ -116,13 +120,13 @@ func isAnagram(s string, t string) bool {
116120
if len(s) != len(t) {
117121
return false
118122
}
119-
var chars [26]int
123+
cnt := [26]int{}
120124
for i := 0; i < len(s); i++ {
121-
chars[s[i]-'a']++
122-
chars[t[i]-'a']--
125+
cnt[s[i]-'a']++
126+
cnt[t[i]-'a']--
123127
}
124-
for _, c := range chars {
125-
if c != 0 {
128+
for _, v := range cnt {
129+
if v != 0 {
126130
return false
127131
}
128132
}
@@ -139,40 +143,49 @@ func isAnagram(s string, t string) bool {
139143
* @return {boolean}
140144
*/
141145
var isAnagram = function (s, t) {
142-
if (s.length != t.length) return false;
143-
let record = new Array(26).fill(0);
144-
let base = 'a'.charCodeAt(0);
146+
if (s.length !== t.length) {
147+
return false;
148+
}
149+
const cnt = new Array(26).fill(0);
145150
for (let i = 0; i < s.length; ++i) {
146-
++record[s.charCodeAt(i) - base];
147-
--record[t.charCodeAt(i) - base];
151+
++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)];
152+
--cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)];
148153
}
149-
return record.every(v => v == 0);
154+
return cnt.every(x => x === 0);
150155
};
151156
```
152157

153158
### **TypeScript**
154159

155160
```ts
156161
function isAnagram(s: string, t: string): boolean {
157-
const n = s.length;
158-
const m = t.length;
159-
return n === m && [...s].sort().join('') === [...t].sort().join('');
162+
if (s.length !== t.length) {
163+
return false;
164+
}
165+
const cnt = new Array(26).fill(0);
166+
for (let i = 0; i < s.length; ++i) {
167+
++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)];
168+
--cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)];
169+
}
170+
return cnt.every(x => x === 0);
160171
}
161172
```
162173

163-
```ts
164-
function isAnagram(s: string, t: string): boolean {
165-
const n = s.length;
166-
const m = t.length;
167-
if (n !== m) {
168-
return false;
169-
}
170-
const count = new Array(26).fill(0);
171-
for (let i = 0; i < n; i++) {
172-
count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
173-
count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--;
174+
### **C#**
175+
176+
```cs
177+
public class Solution {
178+
public bool IsAnagram(string s, string t) {
179+
if (s.Length != t.Length) {
180+
return false;
181+
}
182+
int[] cnt = new int[26];
183+
for (int i = 0; i < s.Length; ++i) {
184+
++cnt[s[i] - 'a'];
185+
--cnt[t[i] - 'a'];
186+
}
187+
return cnt.All(x => x == 0);
174188
}
175-
return count.every(v => v === 0);
176189
}
177190
```
178191

solution/0200-0299/0242.Valid Anagram/README_EN.md

+60-45
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@
2929

3030
## Solutions
3131

32+
**Approach 1: Counting**
33+
34+
We first determine whether the length of the two strings is equal. If they are not equal, the characters in the two strings must be different, so return `false`.
35+
36+
Otherwise, we use a hash table or an array of length $26$ to record the number of times each character appears in the string $s$, and then traverse the other string $t$. Each time we traverse a character, we subtract the number of times the corresponding character appears in the hash table by one. If the number of times after subtraction is less than $0$, the number of times the character appears in the two strings is different, return `false`. If after traversing the two strings, all the character counts in the hash table are $0$, it means that the characters in the two strings appear the same number of times, return `true`.
37+
38+
The time complexity is $O(n)$, the space complexity is $O(C)$, where $n$ is the length of the string; and $C$ is the size of the character set, which is $C=26$ in this problem.
39+
3240
<!-- tabs:start -->
3341

3442
### **Python3**
@@ -38,11 +46,12 @@ class Solution:
3846
def isAnagram(self, s: str, t: str) -> bool:
3947
if len(s) != len(t):
4048
return False
41-
chars = [0] * 26
42-
for i in range(len(s)):
43-
chars[ord(s[i]) - ord('a')] += 1
44-
chars[ord(t[i]) - ord('a')] -= 1
45-
return all(c == 0 for c in chars)
49+
cnt = Counter(s)
50+
for c in t:
51+
cnt[c] -= 1
52+
if cnt[c] < 0:
53+
return False
54+
return True
4655
```
4756

4857
### **Java**
@@ -53,13 +62,13 @@ class Solution {
5362
if (s.length() != t.length()) {
5463
return false;
5564
}
56-
int[] chars = new int[26];
65+
int[] cnt = new int[26];
5766
for (int i = 0; i < s.length(); ++i) {
58-
++chars[s.charAt(i) - 'a'];
59-
--chars[t.charAt(i) - 'a'];
67+
++cnt[s.charAt(i) - 'a'];
68+
--cnt[t.charAt(i) - 'a'];
6069
}
61-
for (int c : chars) {
62-
if (c != 0) {
70+
for (int i = 0; i < 26; ++i) {
71+
if (cnt[i] != 0) {
6372
return false;
6473
}
6574
}
@@ -74,18 +83,15 @@ class Solution {
7483
class Solution {
7584
public:
7685
bool isAnagram(string s, string t) {
77-
if (s.size() != t.size())
86+
if (s.size() != t.size()) {
7887
return false;
79-
vector<int> chars(26, 0);
80-
for (int i = 0, n = s.size(); i < n; ++i) {
81-
++chars[s[i] - 'a'];
82-
--chars[t[i] - 'a'];
8388
}
84-
for (int c : chars) {
85-
if (c != 0)
86-
return false;
89+
vector<int> cnt(26);
90+
for (int i = 0; i < s.size(); ++i) {
91+
++cnt[s[i] - 'a'];
92+
--cnt[t[i] - 'a'];
8793
}
88-
return true;
94+
return all_of(cnt.begin(), cnt.end(), [](int x) { return x == 0; });
8995
}
9096
};
9197
```
@@ -97,13 +103,13 @@ func isAnagram(s string, t string) bool {
97103
if len(s) != len(t) {
98104
return false
99105
}
100-
var chars [26]int
106+
cnt := [26]int{}
101107
for i := 0; i < len(s); i++ {
102-
chars[s[i]-'a']++
103-
chars[t[i]-'a']--
108+
cnt[s[i]-'a']++
109+
cnt[t[i]-'a']--
104110
}
105-
for _, c := range chars {
106-
if c != 0 {
111+
for _, v := range cnt {
112+
if v != 0 {
107113
return false
108114
}
109115
}
@@ -120,40 +126,49 @@ func isAnagram(s string, t string) bool {
120126
* @return {boolean}
121127
*/
122128
var isAnagram = function (s, t) {
123-
if (s.length != t.length) return false;
124-
let record = new Array(26).fill(0);
125-
let base = 'a'.charCodeAt(0);
129+
if (s.length !== t.length) {
130+
return false;
131+
}
132+
const cnt = new Array(26).fill(0);
126133
for (let i = 0; i < s.length; ++i) {
127-
++record[s.charCodeAt(i) - base];
128-
--record[t.charCodeAt(i) - base];
134+
++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)];
135+
--cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)];
129136
}
130-
return record.every(v => v == 0);
137+
return cnt.every(x => x === 0);
131138
};
132139
```
133140

134141
### **TypeScript**
135142

136143
```ts
137144
function isAnagram(s: string, t: string): boolean {
138-
const n = s.length;
139-
const m = t.length;
140-
return n === m && [...s].sort().join('') === [...t].sort().join('');
145+
if (s.length !== t.length) {
146+
return false;
147+
}
148+
const cnt = new Array(26).fill(0);
149+
for (let i = 0; i < s.length; ++i) {
150+
++cnt[s.charCodeAt(i) - 'a'.charCodeAt(0)];
151+
--cnt[t.charCodeAt(i) - 'a'.charCodeAt(0)];
152+
}
153+
return cnt.every(x => x === 0);
141154
}
142155
```
143156

144-
```ts
145-
function isAnagram(s: string, t: string): boolean {
146-
const n = s.length;
147-
const m = t.length;
148-
if (n !== m) {
149-
return false;
150-
}
151-
const count = new Array(26).fill(0);
152-
for (let i = 0; i < n; i++) {
153-
count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
154-
count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--;
157+
### **C#**
158+
159+
```cs
160+
public class Solution {
161+
public bool IsAnagram(string s, string t) {
162+
if (s.Length != t.Length) {
163+
return false;
164+
}
165+
int[] cnt = new int[26];
166+
for (int i = 0; i < s.Length; ++i) {
167+
++cnt[s[i] - 'a'];
168+
--cnt[t[i] - 'a'];
169+
}
170+
return cnt.All(x => x == 0);
155171
}
156-
return count.every(v => v === 0);
157172
}
158173
```
159174

Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
class Solution {
22
public:
33
bool isAnagram(string s, string t) {
4-
if (s.size() != t.size())
4+
if (s.size() != t.size()) {
55
return false;
6-
vector<int> chars(26, 0);
7-
for (int i = 0, n = s.size(); i < n; ++i) {
8-
++chars[s[i] - 'a'];
9-
--chars[t[i] - 'a'];
106
}
11-
for (int c : chars) {
12-
if (c != 0)
13-
return false;
7+
vector<int> cnt(26);
8+
for (int i = 0; i < s.size(); ++i) {
9+
++cnt[s[i] - 'a'];
10+
--cnt[t[i] - 'a'];
1411
}
15-
return true;
12+
return all_of(cnt.begin(), cnt.end(), [](int x) { return x == 0; });
1613
}
1714
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
public class Solution {
2+
public bool IsAnagram(string s, string t) {
3+
if (s.Length != t.Length) {
4+
return false;
5+
}
6+
int[] cnt = new int[26];
7+
for (int i = 0; i < s.Length; ++i) {
8+
++cnt[s[i] - 'a'];
9+
--cnt[t[i] - 'a'];
10+
}
11+
return cnt.All(x => x == 0);
12+
}
13+
}

solution/0200-0299/0242.Valid Anagram/Solution.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ func isAnagram(s string, t string) bool {
22
if len(s) != len(t) {
33
return false
44
}
5-
var chars [26]int
5+
cnt := [26]int{}
66
for i := 0; i < len(s); i++ {
7-
chars[s[i]-'a']++
8-
chars[t[i]-'a']--
7+
cnt[s[i]-'a']++
8+
cnt[t[i]-'a']--
99
}
10-
for _, c := range chars {
11-
if c != 0 {
10+
for _, v := range cnt {
11+
if v != 0 {
1212
return false
1313
}
1414
}

0 commit comments

Comments
 (0)