859. Buddy Strings(python+cpp)
阿新 • • 發佈:2018-11-09
題目:
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
Note:
0 <= A.length <= 20000 0 <= B.length <= 20000
A
andB
consist only of lowercase letters.
解釋:
如果A和B長度不相等,一定是false
如果A和B相等,那麼A中一定要有重複元素,而且交換的時候交換重複元素才能true。
如果A和B僅僅是長度相等而本身不相等,那麼順序遍歷,若A[i]和B[i]不相等,則記錄這對,最後不相等的一定要是兩對,而且這兩對互為相反。
python程式碼:
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A)!=len(B):
return False
if A==B and len(A)!=len(set(A)):
return True
dif=[(a,b) for a,b in zip(A, B) if a!=b]
return len(dif)==2 and dif[0]==dif[1][::-1]
c++程式碼:
class Solution {
public:
bool buddyStrings(string A, string B) {
int len_A=A.size(),len_B=B.size();
set<int>set_A(A.begin(),A.end());
if(len_A!=len_B)
return false;
if(A==B && len_A!=set_A.size())
return true;
vector<vector<char>>dif;
for(int i=0;i<len_A;i++)
{
if (A[i]!=B[i])
{
dif.push_back({A[i],B[i]});
}
}
if (dif.size()!=2)
return false;
vector<char> dif1=dif[1];
reverse(dif1.begin(),dif1.end());
return dif[0]==dif1;
}
};
總結: