20221011 - 1790. Check if One String Swap Can Make Strings Equal(字符串)

90 阅读1分钟

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.

Solution

比昨天那个困难动规简单多了。设置三个变量:不同字符数,出现两个不同字符数的位置。

遍历字符串,遇到不同字符 diff++ ,一旦 diff > 2 说明超过两个字符有差异直接返回 false

diff == 1 时第一个不同字符位置为 i1

diff == 2 时第二个不同字符位置为 i2

遍历完字符串后如果字符串已经相同返回 flase

如果只有一个字符不同返回 false

如果发现交换两个字符不能使字符串相等返回 false

bool areAlmostEqual(char * s1, char * s2){
    int i, i1, i2, diff;
    diff = 0;
    for (i = 0; s1[i]; i++) {
        if (s1[i] != s2[i]) {
            diff++;
            if (diff == 1) i1 = i;
            else if (diff == 2) i2 = i;
        }
        if (diff > 2) return false;
    }
    if (diff == 0) return true;
    else if (diff != 2) return false;
    return (s1[i1] == s2[i2] && s1[i2] == s2[i1]);
}

题目链接:1790. 仅执行一次字符串交换能否使两个字符串相等 - 力扣(LeetCode)