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].
0 and 2 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 * 104s and goal consist of lowercase letters.题目要求两个string,能否通过只交换两个字符来变成另一个string。想来其实很简单,计算一下有几个字符不同,然后看看他们的下标是否能交换就行了。但是实际写起来踩了不少坑:
1. 在"aa"和"aa"这种情况,diffCount = 0,所以需要判断两个string是否相同,如果是相同的string那就要看这个string里有没有重复出现两或以上的字符
2. 最开始写的时候,在循环里面就判断了if diffCount == 2直接看是否能swap就return,其实又可能到这儿都是符合的但是后面就不对应了,所以只能最后return了
3. char[diffCount]写成了char[i]……
- class Solution {
- public boolean buddyStrings(String s, String goal) {
- int diffCount = 0;
- char[] diffS = new char[2];
- char[] diffGoal = new char[2];
- Set<Character> set = new HashSet<>();
- boolean repeat = false;
- if (s.length() != goal.length()) {
- return false;
- }
- for (int i = 0; i < s.length(); i++) {
- if (set.contains(s.charAt(i))) {
- repeat = true;
- }
- set.add(s.charAt(i));
- if (s.charAt(i) != goal.charAt(i)) {
- if (diffCount < 2) {
- diffS[diffCount] = s.charAt(i);
- diffGoal[diffCount] = goal.charAt(i);
- }
- diffCount++;
- }
- }
- if (diffCount == 0) {
- return repeat;
- } else if (diffCount == 2) {
- return diffS[0] == diffGoal[1] && diffS[1] == diffGoal[0];
- }
- return false;
- }
- }