-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidAnagram_242.java
More file actions
68 lines (61 loc) · 1.82 KB
/
Copy pathValidAnagram_242.java
File metadata and controls
68 lines (61 loc) · 1.82 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.leetcode.string;
import java.util.HashMap;
import java.util.Map;
/**
* Created by charles on 3/28/17.
* Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
*/
public class ValidAnagram_242 {
/** if there is no unicode, only english letters */
public boolean isAnagram(String s, String t) {
int[] table = new int[26];
if (s.length() != t.length()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
table[t.charAt(i) - 'a']--;
}
for (int num : table) {
if (num != 0) {
return false;
}
}
return true;
}
public boolean isAnagramII(String s, String t) {
Map<Character, Integer> map = new HashMap<>();
if (s.length() != t.length()) {
return false;
}
char sChar;
char tChar;
for (int i = 0; i < s.length(); i++) {
sChar = s.charAt(i);
tChar = t.charAt(i);
if (map.containsKey(sChar)) {
map.put(sChar, map.get(sChar) + 1);
} else {
map.put(sChar, 1);
}
if (map.containsKey(tChar)) {
map.put(tChar, map.get(tChar) - 1);
} else {
map.put(tChar, -1);
}
}
for (Character character : map.keySet()) {
if (map.get(character) != 0) {
return false;
}
}
return true;
}
}