我又回来了,继续刷算法,可能的话,英文也想加强一下。由于好久没有刷了,先把新增的几个easy级别题目做了。首先看下面这题:

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:

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

这题粗看没看出什么解法,它的正确率还是挺低的,才百分之二十多貌似。所以这题肯定有陷阱。想了一下发现其实不难,只要字符串有2个不一样的地方并且它们的字符换了之后相等,那么必定符合题意;同时有一种特殊情况,主要是整个字符串都相等的情况下,只有这个字符串有任意的字符出现两次及以上,那么也是符合题意的。直接上代码:

static bool Main(std::string A, std::string B) {
        if (A.size() != B.size()) {
            return false;
        }
        int nCharCnt[26] = {0};
        int nNotEqualCharPos[2] = {0};

        int nNotEqualCount = 0;
        bool bCharDunp = false;
        for (std::size_t i = 0; i < A.size(); i++) {
            if (A[i] != B[i]) {
                nNotEqualCount++;
                if (nNotEqualCount > 2) {
                    return false;
                }
                nNotEqualCharPos[nNotEqualCount - 1] = i;
            } else {
                nCharCnt[A[i] - 'a']++;
                if (nCharCnt[A[i] - 'a'] >= 2) {
                    bCharDunp = true;
                }
            }
        }
        if (nNotEqualCount == 2) {
            if (A[nNotEqualCharPos[0]] == B[nNotEqualCharPos[1]] &&
                A[nNotEqualCharPos[1]] == B[nNotEqualCharPos[0]]) {
                return true;
            }
            return false;
        }
        if (nNotEqualCount == 0) {
            // Check the char count
            return bCharDunp;
        }

        return false;
    }
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day