分析:2つの文字列の文字数が等しくない場合、falseが返されます。以下の他の状況は、2つの文字列の同じ文字数に基づいています。
2つの文字列の同じ位置にある同じ文字数が、文字の総数から3を引いた数以下の場合、falseを返す必要があります。
2つの文字列の同じ位置にある同じ文字数が、文字の総数から1を引いた数に等しい場合、falseを返す必要があります。
2つの文字列の同じ位置にある同じ文字数が文字の総数と等しい場合は、ケースについて説明します。重複する文字がある場合はtrueを返し、そうでない場合はfalseを返します。
2つの文字列の同じ位置にある同じ文字数が文字の総数から2を引いたものに等しい場合、trueを返すのは、残りの2つのスワップ位置の後で文字列の1つを他の文字列とペアリングできるかどうかを確認することです。 !!
class Solution {
public boolean buddyStrings(String A, String B) {
char [] a = A.toCharArray();
char [] b = B.toCharArray();
if(a.length != b.length){
return false;
}
int length = a.length;
int [] m = new int[length];
int [] n = new int[length];
for(int i = 0;i < length;i++){
m[i] = a[i] -'a' + 1;
}
for(int j = 0;j < length;j++){
n[j] = b[j] - 'a' + 1;
}
int count = 0;
ArrayList<Integer> mList = new ArrayList();
ArrayList<Integer> nList = new ArrayList();
for(int k = 0;k < length;k++){
if(m[k] == n[k]){
count++;
}else{
mList.add(m[k]);
nList.add(n[k]);
}
}
if(count <= length -3 || count == length - 1){
return false;
}
if(count == length){
HashSet set = new HashSet();
for(int p = 0;p < length;p++){
if(set.contains(m[p])){
return true;
}
set.add(m[p]);
}
return false;
}
if(count == length -2){
if(mList.get(1) == nList.get(0) && mList.get(0) == nList.get(1)){
return true;
}else{
return false;
}
}
return false;
}
}
時間計算量はO(n)です。