Skip to content

Commit 0c2d297

Browse files
committed
finish 242
1 parent 6ed4117 commit 0c2d297

File tree

1 file changed

+110
-0
lines changed

1 file changed

+110
-0
lines changed

201-300/242. Valid Anagram.md

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# 242. Valid Anagram
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Hash Table, Sort.
5+
- Similar Questions: Group Anagrams, Palindrome Permutation, Find All Anagrams in a String.
6+
7+
## Problem
8+
9+
Given two strings **s** and ****, write a function to determine if **t** is an anagram of **s**.
10+
11+
**Example 1:**
12+
13+
```
14+
Input: s = "anagram", t = "nagaram"
15+
Output: true
16+
```
17+
18+
**Example 2:**
19+
20+
```
21+
Input: s = "rat", t = "car"
22+
Output: false
23+
```
24+
25+
**Note:**
26+
You may assume the string contains only lowercase alphabets.
27+
28+
**Follow up:**
29+
What if the inputs contain unicode characters? How would you adapt your solution to such case?
30+
31+
32+
## Solution 1
33+
34+
```javascript
35+
/**
36+
* @param {string} s
37+
* @param {string} t
38+
* @return {boolean}
39+
*/
40+
var isAnagram = function(s, t) {
41+
var lenA = s.length;
42+
var lenB = t.length;
43+
var map = {};
44+
45+
if (lenA !== lenB) return false;
46+
47+
for (var i = 0; i < lenA; i++) {
48+
if (!map[s[i]]) map[s[i]] = 0;
49+
map[s[i]]++;
50+
}
51+
52+
for (var j = 0; j < lenB; j++) {
53+
if (!map[t[j]]) return false;
54+
map[t[j]]--;
55+
}
56+
57+
return true;
58+
};
59+
```
60+
61+
**Explain:**
62+
63+
nope.
64+
65+
**Complexity:**
66+
67+
* Time complexity : O(n).
68+
* Space complexity : O(n).
69+
70+
## Solution 2
71+
72+
```javascript
73+
/**
74+
* @param {string} s
75+
* @param {string} t
76+
* @return {boolean}
77+
*/
78+
var isAnagram = function(s, t) {
79+
var lenA = s.length;
80+
var lenB = t.length;
81+
var map = Array(26);
82+
var index = 0;
83+
var base = 'a'.charCodeAt(0);
84+
85+
if (lenA !== lenB) return false;
86+
87+
for (var i = 0; i < lenA; i++) {
88+
index = s[i].charCodeAt(0) - base;
89+
if (!map[index]) map[index] = 0;
90+
map[index]++;
91+
}
92+
93+
for (var j = 0; j < lenB; j++) {
94+
index = t[j].charCodeAt(0) - base;
95+
if (!map[index]) return false;
96+
map[index]--;
97+
}
98+
99+
return true;
100+
};
101+
```
102+
103+
**Explain:**
104+
105+
nope.
106+
107+
**Complexity:**
108+
109+
* Time complexity : O(n).
110+
* Space complexity : O(1).

0 commit comments

Comments
 (0)