forked from HairuoLiu/Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC859_BuddyStrings.java
More file actions
77 lines (70 loc) · 1.74 KB
/
Copy pathLC859_BuddyStrings.java
File metadata and controls
77 lines (70 loc) · 1.74 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
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
*
* Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
*
*
* Example 1:
*
* Input: A = "ab", B = "ba"
* Output: true
* Example 2:
*
* Input: A = "ab", B = "ab"
* Output: false
* Example 3:
*
* Input: A = "aa", B = "aa"
* Output: true
* Example 4:
*
* Input: A = "aaaaaaabc", B = "aaaaaaacb"
* Output: true
* Example 5:
*
* Input: A = "", B = "aa"
* Output: false
*
* @author Liu.3502
* @created 2018-03-24 下午12:08
*/
public class LC859_BuddyStrings{
public static void main(String[] args) {
String a ="abc";
String b ="abc";
boolean result = buddyStrings(a,b);
System.out.println("result的值是:" + result);
}
public static boolean buddyStrings(String A, String B) {
if(A.length() != B.length()){
return false;
}
if(A.equals(B)){
Set<Character> set =new HashSet<>();
for(char i : A.toCharArray()){
set.add(i);
}
return set.size() < A.length();
}
char AF='-',BF='+',AS='?',BS='/';
int diff = 0;
for(int i = 0; i < A.length(); ++i){
if(diff >= 2){
return false;
}
if(diff == 0 && A.charAt(i) != B.charAt(i)){
AF = A.charAt(i);
BF = B.charAt(i);
diff++;
}else if(diff ==1 && A.charAt(i) != B.charAt(i)){
AS = A.charAt(i);
BS = B.charAt(i);
diff++;
}
}
return AF == BS && AS == BF;
}
}