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
0and2in"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 * 104sandgoalconsist of lowercase letters.
思路:
- Using 2 indices
diff1,diff2to store up to 2 different places between stringAand 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
Acontains 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) {
if(s.length() != goal.length()) {
return false;
}
int first = -1; int second = -1;
HashSet<Character> set = new HashSet<>();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != goal.charAt(i)) {
if(first == -1) {
first = i;
} else if(second == -1) {
second = i;
} else { // 3 diff;
return false;
}
}
set.add(s.charAt(i));
}
if(first != -1 && second != -1) {
return s.charAt(first) == goal.charAt(second)
&& s.charAt(second) == goal.charAt(first);
}
if(first != -1 && second == -1) {
return false;
}
return set.size() < s.length(); // set size 小于len,说明有至少一个重复,可以互换;
}
}










