-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path22. Determine if Two Strings Are Close
77 lines (61 loc) · 1.76 KB
/
22. Determine if Two Strings Are Close
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
69
70
71
72
73
74
75
76
77
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length()!=word2.length()) return false;
int[] w1=new int[26];
int[] w2=new int[26];
for(char c:word1.toCharArray()){
w1[c-'a']++;
}
for(char c:word2.toCharArray()){
w2[c-'a']++;
}
//Step1:
for(int i=0;i<26;i++){
if((w1[i]==0 && w2[i]!=0) || (w1[i]!=0 && w2[i]==0)){
return false;
}
}
//Step 2:
Map<Integer,Integer> map=new HashMap<>();
for(int i:w1){
if(i>0){
map.put(i,map.getOrDefault(i,0)+1);
}
}
for(int i:w2){
if(i>0){
if(!map.containsKey(i)){
return false;
}
map.put(i,map.get(i)-1);
if(map.get(i)==0){
map.remove(i);
}
}
}
return map.size()==0;
}
}
class Solution {
public boolean closeStrings(String word1, String word2) {
if(word1.length()!=word2.length()) return false;
int[] w1=new int[26];
int[] w2=new int[26];
for(char c:word1.toCharArray()){
w1[c-'a']++;
}
for(char c:word2.toCharArray()){
w2[c-'a']++;
}
//Step1:
for(int i=0;i<26;i++){
if((w1[i]==0 && w2[i]!=0) || (w1[i]!=0 && w2[i]==0)){
return false;
}
}
//Step 2:
Arrays.sort(w1);
Arrays.sort(w2);
return Arrays.equals(w1,w2);
}
}