forked from akshayysharma/hacktoberfest-2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuddy-strings.java
More file actions
48 lines (41 loc) · 1.54 KB
/
buddy-strings.java
File metadata and controls
48 lines (41 loc) · 1.54 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
/*
solution to Buddy Strings at leetcode in Java.
Author : Neha Labhasetwar.
Ref : https://leetcode.com/problems/buddy-strings
Description:
Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad".
Example1:
Input: A = "ab", B = "ba"
Output: true
Example2:
Input: A = "ab", B = "ab"
Output: false
*/
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length()) return false;
if (A.equals(B)) {
int[] count = new int[26];
for (int i = 0; i < A.length(); ++i)
count[A.charAt(i) - 'a']++;
for (int c: count)
if (c > 1) return true;
return false;
} else {
int first = -1, second = -1;
for (int i = 0; i < A.length(); ++i) {
if (A.charAt(i) != B.charAt(i)) {
if (first == -1)
first = i;
else if (second == -1)
second = i;
else
return false;
}
}
return (second != -1 && A.charAt(first) == B.charAt(second) &&
A.charAt(second) == B.charAt(first));
}
}
}