Given two strings s
and goal
, return true
if you can swap two letters in s
so the result is equal to goal
, 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 s[i]
and s[j]
.
- For example, swapping at indices
0
and2
in"abcd"
results in"cbad"
.
Example 1:
Input: s = "ab", goal = "ba" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
Input: s = "ab", goal = "ab" Output: false Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
Input: s = "aa", goal = "aa" Output: true Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Constraints:
1 <= s.length, goal.length <= 2 * 104
s
andgoal
consist of lowercase letters.
思路:
- Using 2 indices
diff1
,diff2
to store up to 2 different places between stringA
and stringB
. - If there are more than 2 different places -> Invalid.
- If there are 2 different places -> Compare A[diff1] vs B[diff2] and A[diff2] vs B[diff1].
- If there is only 1 different places -> Invalid.
- If no difference between A and B then check if
A
contains at least 1 duplicate letters so that we can swap them.- Example 1:
A = "ab"
,B = "ab"
- Example 2:
A = "aab"
,B = "aab"
,
- Example 1:
class Solution {
public boolean buddyStrings(String s, String goal) {
int first = -1; int second = -1;
HashSet<Character> set = new HashSet<>();
if(s.length() != goal.length()) {
return false;
}
for(int i = 0; i < s.length(); i++) {
char sc = s.charAt(i);
char gc = goal.charAt(i);
if(sc != gc) {
if(first == -1) {
first = i;
} else if(second == -1) {
second = i;
} else {
return false;
}
}
set.add(sc);
}
// s != goal
if(first != -1 && second != -1) {
if( s.charAt(first) == goal.charAt(second)
&& s.charAt(second) == goal.charAt(first) ) {
return true;
}
}
// s == goal, then s should have at least 2 duplicate chars;
return s.equals(goal) && set.size() < goal.length();
}
}