题目描述:
给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。
示例 1:
输入: A = “ab”, B = “ba”
输出: true
示例 2:
输入: A = “ab”, B = “ab”
输出: false
示例 3:
输入: A = “aa”, B = “aa”
输出: true
示例 4:
输入: A = “aaaaaaabc”, B = “aaaaaaacb”
输出: true
示例 5:
输入: A = “”, B = “aa”
输出: false
提示:
0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。
感觉有点繁琐了,分的情况有点多
代码
class Solution {
public boolean buddyStrings(String A, String B) {
if(A.length() != B.length()){
return false;
}
//如果A和B是相等的,那么只有A中有重复的字符串那么才可能符合题目意思
if(A.equals(B)){
int tem[] = new int[26];
for (int i = 0; i < A.length(); i++) {
tem[A.charAt(i) - 97] ++;
if(tem[A.charAt(i) - 97] > 1){
return true;
}
}
return false;
}
int index = 0;
//time记录的是改变了多少次数
int time = 0;
int startA = 0;
char [] Atem = A.toCharArray();
char [] Btem = B.toCharArray();
while (index < A.length()) {
if(A.charAt(index) != B.charAt(index)){
if(time == 2){
return false;
}
if(time == 0){
//记录下首个不相等的下标
startA = index;
}
time ++;
if(time == 2){
if(!(Atem[startA] == Btem[index] && Atem[index] == Btem[startA]))
return false;
}
}
index++;
}
return true;
}
}
效率还行
排名靠前的
思路跟我的基本一样啊
class Solution {
public boolean buddyStrings(String A, String B) {
if (A.length() != B.length())
return false;
char[] a = A.toCharArray();
char[] b = B.toCharArray();
if (A.equals(B)) {
byte[] bucket = new byte[200];
for (int i = 0; i < a.length; i++) {
if (bucket[a[i]] != 0) {
return true;
} else {
bucket[a[i]]++;
}
}
return false;
} else {
int index1 = -1, index2 = -1, cnt = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) {
cnt++;
if (cnt > 2) {
return false;
}
if (index1 == -1) {
index1 = i;
} else {
index2 = i;
}
}
}
if (a[index1] == b[index2] && b[index1] == a[index2]) {
return true;
}
return false;
}
}
}