Buddy Strings

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 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 * 104
  • s and goal consist of lowercase letters.

思路:

  • Using 2 indices diff1diff2 to store up to 2 different places between string A and string B.
  • 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 A contains at least 1 duplicate letters so that we can swap them.
    • Example 1: A = "ab"B = "ab"
    • Example 2: A = "aab"B = "aab",
class Solution {
    public boolean buddyStrings(String s, String goal) {
        int first = -1; int second = -1;
        HashSet<Character> set = new HashSet<>();
        if(s.length() != goal.length()) {
            return false;
        }
        for(int i = 0; i < s.length(); i++) {
            char sc = s.charAt(i);
            char gc = goal.charAt(i);
            if(sc != gc) {
                if(first == -1) {
                    first = i;
                } else if(second == -1) {
                    second = i;
                } else {
                    return false;
                }
            }
            set.add(sc);
        }
        
        // s != goal
        if(first != -1 && second != -1) {
            if( s.charAt(first) == goal.charAt(second)
                && s.charAt(second) == goal.charAt(first) ) {
                return true;
            }
        }
        
        // s == goal, then s should have at least 2 duplicate chars;
        return s.equals(goal) && set.size() < goal.length();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值