859. Buddy Strings
Given two strings A
and B
of lowercase letters, return true
if you can swap two letters in A
so the result is equal to B
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at A[i]
and A[j]
. For example, swapping at indices 0
and 2
in "abcd"
results in "cbad"
.
Example 1:
Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B.
Example 2:
Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B.
Example 3:
Input: A = "aa", B = "aa" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B.
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true
Example 5:
Input: A = "", B = "aa" Output: false
Constraints:
0 <= A.length <= 20000
0 <= B.length <= 20000
A
andB
consist of lowercase letters.
class Solution { public boolean buddyStrings(String A, String B) { int n1 = A.length(), n2 = B.length(); if(n1 != n2 || n1 == 0 || n2 == 0) return false; if(A.equals(B)) { int[] count = new int[26]; for(char c : A.toCharArray()) count[c - 'a']++; for(int i : count) { if(i > 1) return true; } return false; } else { int fir = -1, sec = -1; for(int i = 0; i < n1; i++) { if(A.charAt(i) != B.charAt(i)) { if(fir == -1) fir = i; else if(sec == -1) sec = i; else return false; } } return sec != -1 && A.charAt(fir) == B.charAt(sec) && A.charAt(sec) == B.charAt(fir); } } }
这也能是easy?泥头车创撕你。
corner case很多,首先当两个相等,判断下里面有没有一个char出现了两次或以上,如果有就返回true,否则返回false,因为不可能符合题意。
如果不相等,也要看是不是只出现了两个位置不相等,而且交换后相等,所以只能判断到第二个不相等的,如果不相等的小于2或者大于2,都返回错误。只有两个不相等的时候,且交换他俩后相等,才能返回true。