[leetcode] 859. Buddy Strings

441 篇文章 0 订阅
284 篇文章 0 订阅

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

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

分析

题目的意思是:有两个字符串,其中一个字符串只交换字符一次,看两个字符串是否相等

  • 这是一道easy类型的题目,开始大家可能都觉得这是一道dp的问题,其实简单解法既可以,废话不多说,直接看代码。
  • 如果字符串A与字符串B不相等,则直接返回false;然后遍历字符串A,B,记录字符串中字符不相等的位置,然后把上面例子的五种情况都考虑到就行了。

代码

class Solution {
public:
    bool buddyStrings(string A, string B) {
        int m=A.length();
        int n=B.length();
        if(m!=n){
            return false;
        }
        int pos=-1;
        bool isSwap=false;
        bool isRepeat=false;
        vector<int> count(26,0);
        for(int i=0;i<m;i++){
            if(A[i]!=B[i]){
                if(pos==-1){
                    pos=i;
                }else if(isSwap||A[pos]!=B[i]||A[i]!=B[pos]){
                    return false;
                }else{
                    isSwap=true;
                }
            }
            if(++count[A[i]-'a']>1) isRepeat=true;
        }
        return isSwap||isRepeat;
    }
    
};

参考文献

859. Buddy Strings

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值