LeetCode#859: Buddy Strings

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83989962

Description

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

Example

Input: A = "ab", B = "ba"
Output: true
Input: A = "ab", B = "ab"
Output: false
Input: A = "aa", B = "aa"
Output: true
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Input: A = "", B = "aa"
Output: false

Note

  • 0 <= A.length <= 20000
  • 0 <= B.length <= 20000
  • A and B consist only of lowercase letters.

Solution

这道题容易忽视两个测试用例String A = "aa"; String B = "aa"String A = "abab"; String B = "abab",这两类情况都应该返回true,发现了这点其实比较好通过。

此题大致分为三种情况:
1、A与B长度不等,这时候肯定返回false。
2、A与B完全相同,则查看字符串中是否有重复的字母,有的话就返回true,因为交换重复的字母不会改变字符串,且满足了题目要求。否则,返回false。
3、A中有且仅有两个字母与B不同,且交换之后就与B相同了,这时候返回true。否则,返回false。

class Solution {
    public boolean buddyStrings(String A, String B) {
        if(A.length() != B.length())
        	return false;
        HashSet<Character> set = new HashSet<>();
        char[] diffA = new char[2];
        char[] diffB = new char[2];
        int index = 0;
        for(int i = 0; i < A.length(); i++) {
        	set.add(A.charAt(i));
        	if(A.charAt(i) != B.charAt(i)){
        		if(index == 2) return false;
        		diffA[index] = A.charAt(i);
        		diffB[index] = B.charAt(i);
        		index++;
        	}
        }
        
        if(index == 2) {
        	return (diffA[0] != 0 && diffA[1] != 0 && diffA[0] == diffB[1] && diffB[0] == diffA[1]);
        } else if(index == 1) {
        	return false;
        } else {
        	return (A.equals(B) && set.size() < A.length());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/83989962