lintcode1510. 亲密字符串

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

样例
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
注意事项
1.0 <= A.length <= 20000
2.0 <= A.length <= 20000
3.A and B consist only of lowercase letters.
class Solution {
public:
    /**
     * @param A: string A
     * @param B: string B
     * @return: bool
     */
    bool buddyStrings(string &A, string &B) {
        // Write your code here
        if(A.size()!=B.size()) return false;
        int count=0;
        int first=-1;
        int second=-1;
        bool judge=false;
        for (int i = 0; i < A.size()&&count<=2; i++) {
            /* code */
            if(A[i]!=B[i])
            {
                count++;
                if(first==-1) first=i;
                else second=i;
            }
            for (int j = i+1; j < A.size(); j++) {
                /* code */
                if(A[i]==A[j]) judge=true;
            }
        }
        if(count==0&&judge) return true;
        if(count!=2) return false;
        if(A[first]==B[second]&&A[second]==B[first]) return true;
        return false;
    }
};
发布了330 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103943731
今日推荐