-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuddyStrings.java
64 lines (56 loc) · 1.72 KB
/
BuddyStrings.java
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
//E
//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".
//Example:
// Input: A = "ab", B = "ba"
// Output: true
// Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
public class BuddyStrings {
public boolean buddyStrings(String A, String B) {
//ab ba
int differences=0;
char temp = 0;
for (int i = 0; i <A.length() ; i++) {
if((A.charAt(i)!=B.charAt(i)))
{
if(differences==2)
{
return false;
}else if(differences==0)
{
differences++;
temp=A.charAt(i);
}
else if(differences==1)
{
if(temp==B.charAt(i))
{
differences++;
}
else
{
return false;
}
}
}
}
if(differences == 2)
{
return true;
}
for (int i = 0; i <A.length() ; i++) {
if(i==0)
{
temp=A.charAt(i);
}else if(temp!=A.charAt(i))
{
return false;
}
}
if(A.equals("") || B.equals(""))
{
return false;
}
return false;
}
}