You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/0200-0299/0242.Valid Anagram/README_EN.md
+60-45
Original file line number
Diff line number
Diff line change
@@ -29,6 +29,14 @@
29
29
30
30
## Solutions
31
31
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.
0 commit comments