leetcode 859 Buddy Strings
阿新 • • 發佈:2018-12-09
python:
class Solution: def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ if A == B: return len(set(A)) != len(A) if len(A) != len(B) or A == B: return False flag = True a = list(A) for i in range(len(A)): if A[i] != B[i]: if flag: flag = False j = i else: a[i], a[j] = a[j], a[i] C = ''.join(k for k in a) print(C) return C == B return False
c++:
class Solution { public: bool buddyStrings(string A, string B) { if (unordered_set<char> (A.begin(), A.end()).size() != A.length() && A == B) return true; if (A == B || A.length()!=B.length()) return false; vector<int> index; int flag = 2; for (int i=0; i<A.length(); i++){ if (A[i] != B[i]){ index.push_back(i); flag--; } } return flag == 0 && (A[index[0]] == B[index[1]] && B[index[0]] == A[index[1]]); } };