LeetCode知识点总结 - 859

LeetCode 859. Buddy Strings

考点难度
Hash TableEasy
题目

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”.

思路

一共需要考虑四个字母s[i]s[j]goal[i]goal[j],分为两种情况:
1 sgoal完全相同,s[i] == s[j] == goal[i] == goal[j],需要找到一个重复出现的字母
2 sgoal不同,需要s[i] == goal[j]s[j] == goal[i]s[i] != s[j]
第一种情况中找重复出现的字母用到的方法是统计26个字母每个字母出现的次数,再遍历这26个数字,如果有一个数字大于0则返回true
第二种情况因为只能允许sgoal有两个字母不一样,如果发现第三个字母也不一样(前两个不一样的情况下)直接返回false。另外sgoal的字母是一一对应的(如果s的第一位是a,goal的第一位不是a则算作一个不同字母)所以遍历的时候用一个i即可。

答案
class Solution {
    public boolean buddyStrings(String s, String goal) {
        if (s.length() != goal.length()) {
            return false;
        }
        if (s.equals(goal)){
            int[] count = new int [26];
            for (int i = 0; i < s.length(); ++i){
                count[s.charAt(i) - 'a']++;
            }
            for (int c: count){
                if (c > 1){
                    return true;
                }
            }
            return false;
        }
        else {
            int first = -1, second = -1;
            for (int i = 0; i < s.length(); ++i){
                if (s.charAt(i) != goal.charAt(i)){
                    if (first == -1){
                        first = i;
                    }
                    else if (second == -1){
                        second = i;
                    }
                    else{
                        return false;
                    }
                }
            }
            return (second != -1 && s.charAt(first) == goal.charAt(second)
                   && s.charAt(second) == goal.charAt(first));
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值