859. Buddy Strings

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 1:

Input: A = “ab”, B = “ba”
Output: true
Example 2:

Input: A = “ab”, B = “ab”
Output: false
Example 3:

Input: A = “aa”, B = “aa”
Output: true
Example 4:

Input: A = “aaaaaaabc”, B = “aaaaaaacb”
Output: true
Example 5:

Input: A = “”, B = “aa”
Output: false

Note:

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

思路:
If A.length() != B.length(): no possible swap

If A == B, we need swap two same characters. Check is duplicated char in A.

In other cases, we find index for A[i] != B[i]. There should be only 2 diffs and it’s our one swap.

代码:

class Solution {
    public  boolean buddyStrings(String A, String B) {

        //Input: A = "", B = "aa"  Output: false
        if(A.length()!=B.length())
            return false;

        //Input: A = "ab", B = "ab"    Output: false
        //Input: A = "aa", B = "aa"    Output: true
        if(A.equals(B)){//去重复
            Set<Character>set=new HashSet<>();
            for(char c:A.toCharArray())
                set.add(c);
            return set.size()<A.length();
        }

        //Input: A = "aaaaaaabc", B = "aaaaaaacb"  Output: true
        List<Integer> dif=new ArrayList<>();
        for (int i = 0; i <A.length() ; i++) {
            if(A.charAt(i)!=B.charAt(i))
                dif.add(i);//记录下标,最多有2个元素
        }

        return dif.size()==2
                &&A.charAt(dif.get(0))==B.charAt(dif.get(1))
                &&A.charAt(dif.get(1))==B.charAt(dif.get(0));
    }  

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值