Skip to content

Commit f30d14a

Browse files
authored
Added leetcode solution for Buddy Strings (#128)
1 parent 8990981 commit f30d14a

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

Java/buddy-strings.java

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Problem Name : Buddy Strings
3+
* Concept Involved : String Manipulation, Frequency Computation, Observation
4+
*
5+
* Execution Time : 2 ms
6+
* Memory Consumed : 39.1 mb
7+
*
8+
*/
9+
class Solution {
10+
public boolean isDuplicate(String str){
11+
int[] fre = new int[26];
12+
for(int i=0; i<str.length(); i++){
13+
int ind = str.charAt(i) - 'a';
14+
fre[ind]++;
15+
if(fre[ind] > 1){
16+
return true;
17+
}
18+
}
19+
return false;
20+
}
21+
public boolean buddyStrings(String A, String B) {
22+
if(A.length() != B.length()){
23+
return false;
24+
}
25+
26+
int count = 0;
27+
char ca = 'A';
28+
char cb = 'A';
29+
30+
for(int i=0; i<A.length(); i++){
31+
if(A.charAt(i) != B.charAt(i) ){
32+
if(count == 0){
33+
ca = A.charAt(i);
34+
cb = B.charAt(i);
35+
}
36+
else if(count == 1){
37+
if(ca != B.charAt(i) || cb != A.charAt(i)){
38+
count++;
39+
}
40+
}
41+
count++;
42+
}
43+
}
44+
45+
if(count == 2 || (count == 0 && isDuplicate(A))){
46+
return true;
47+
}
48+
return false;
49+
}
50+
}

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
143143
| 1221 | [Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/) | [Python](./Python/split-a-string-in-balanced-strings.py) | _O(n)_ | _O(1)_ | Easy | | |
144144
| 1614 | [Maximum Nesting Depth of the Parentheses](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/) | [Java](./Java/max-nesting-depth-parentheses.java) | _O(n)_ | _O(1)_ | Easy | | |
145145
| 1374 | [Generate a String With Characters That Have Odd Counts](https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/) | [Java](./Java/generate-a-string-with-characters-that-have-odd-counts.java) | _O(n)_ | _O(1)_ | Easy | | |
146-
146+
| 859 | [Buddy Strings](https://leetcode.com/problems/buddy-strings/) | [Java](./Java/buddy-strings.java) | _O(n)_ | _O(1)_ | Easy | | |
147147
<br/>
148148
<div align="right">
149149
<b><a href="#algorithms">⬆️ Back to Top</a></b>

0 commit comments

Comments
 (0)