Leetcode 859 Buddy Strings

Leetcode 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 and B consist of lowercase letters.

思路

根据上面的例子可以看出一共分为两种情况,第一种是两个字符串只有两个字符不同,且这两个字符是互换位置的;第二种是两个字符串相同,但是中间含有重复的字符,这样可以交换重复的字符。
所以代码先考虑第一种情况,比较是否有字符不同,有的话第一次修改index,根据index就可以判断当前到底是第一次还是第二次的字符不同,到了第二次的时候,直接判断是否互换且后面字符串相等。
结束该循环后有两种情况,index!=1则说明两个字符串中只有一个字符不同(因为遇到第二个不同是无论如何都会返回),此时直接返回false;否则说明两个字符串完全相同,接下来计数计算一下是否存在重复字符,有的话返回true。

代码

class Solution {
    public boolean buddyStrings(String A, String B) {
        if (A.length() != B.length()) return false;
        int index = -1;
        for (int i = 0; i < A.length(); i++) {
            if (A.charAt(i) != B.charAt(i)) {
                if (index == -1) {
                    index = i;
                } else {
                    return (A.charAt(i) == B.charAt(index) && A.charAt(index) == B.charAt(i) && A.substring(i+1).equals(B.substring(i+1)));
                }
            }
        }
        if (index != -1) return false;// only one number differs
        int[] count = new int[26];
        for (int i = 0; i < A.length(); i++) {
            if (count[A.charAt(i) - 'a'] != 0) {
                return true;
            } else {
                count[A.charAt(i) - 'a']++;
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值