LintCode 题目:亲密字符串

URL:https://www.lintcode.com/problem/buddy-strings/description

描述

给定两个由小写字母构成的字符串AB,只要我们可以通过交换A中的两个字母得到与B相等的结果,就返回true;否则返回false

1.0 <= A.length <= 20000
2.0 <= A.length <= 20000
3.A and B consist only of lowercase letters.

您在真实的面试中是否遇到过这个题?  

样例

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

思路:

  • 如果A和B长度是否相等,长度不等,直接返回false;
  • 如果A和B相等,查看A中是否有相同的字母,若有则返回true;否则返回false;
  • 将A和B中不相等的字母记录下来,如果不相等字母的数目不等于2直接返回false;
  • 比较A和B不同的字母交换后是否相等,若相等返回true;否则返回false;

在代码段中添加:

int a = A.size(),b = B.size();
        if(a!=b)
            return false;
        if(A==B){
            for (int i = 0; i < a; i++) {
                if(count(A.begin(),A.end(),A[i])>1||count(B.begin(),B.end(),B[i])>1)
                    return true;
                else
                    return false;
            }
        }
        int j=0;
        char sa[3],sb[3];
        for (int i = 0; i < a; i++) {
            /* code */
            if(A[i]!=B[i]){
                sa[j] = A[i];
                sb[j] = B[i];
                j++;
            }
        }
        if(j!=2)
            return false;
        if(sa[1]==sb[0]&&sa[0]==sb[1])
            return true;
        else
            return false;
    }

即可:

发布了303 篇原创文章 · 获赞 550 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_42410605/article/details/103103026