-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuddyStrings.java
More file actions
29 lines (24 loc) · 785 Bytes
/
BuddyStrings.java
File metadata and controls
29 lines (24 loc) · 785 Bytes
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
//859. Buddy Strings
class Solution {
public boolean buddyStrings(String s, String goal) {
if(s.length()!=goal.length()) return false;
if(s.equals(goal)){
int[] freq=new int[26];
for(char ch:s.toCharArray()){
freq[ch-'a']++;
if(freq[ch-'a']>1) return true;
}
return false;
}
int first=-1,second=-1;
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=goal.charAt(i)){
if(first==-1) first=i;
else if(second==-1) second=i;
else return false;
}
}
if(second==-1) return false;
return s.charAt(first)==goal.charAt(second) && s.charAt(second)==goal.charAt(first);
}
}