You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

 

Example 1:

Input: s1 = "bank", s2 = "kanb"
Output: true
Explanation: For example, swap the first character with the last character of s2 to make "bank".
Example 2:

Input: s1 = "attack", s2 = "defend"
Output: false
Explanation: It is impossible to make them equal with one string swap.
Example 3:

Input: s1 = "kelb", s2 = "kelb"
Output: true
Explanation: The two strings are already equal, so no string swap operation is required.
 

Constraints:

1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1 and s2 consist of only lowercase English letters.

这题也是难度比较低的一题,题意是给出两个字符串,假设一个字符串最多做一次的字符交换能与另一个字符串相等,那么符合题意。

所以假设一个字符串和另一个字符串相等,那么肯定是OK的,然后假设只有两个字符不一样,只要它们交换后能相等,那么也可以。

所以我们找出不一样的字符索引,然后看看它们是否一样即可。为了速度最快,我们用O(N)的算法一次遍历来实现:

class Solution {
public:
    bool areAlmostEqual(std::string s1, std::string s2) {
        if (s1.size() != s2.size()) return false;
        int diffidx = -1;

        for (size_t i = 0; i < s1.size(); i++) {
            if (s1[i] != s2[i]) {
                if (diffidx == -2) return false;
                if (diffidx == -1) {
                    diffidx = i;
                } else {
                    if (s1[i] != s2[diffidx] || s1[diffidx] != s2[i]) return false;
                    diffidx = -2;
                }
            }
        }
        return diffidx == -1 || diffidx == -2;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day