1790. Check if One String Swap Can Make Strings Equal

1790. Check if One String Swap Can Make Strings Equal #

题目 #

  • 给定长度相等的两个字符串 s1s2
  • 一次字符串交换操作的步骤为:选出某个字符串中的两个下标,并交换这两个下标对应的字符。
  • 如果对其中一个字符串执行最多一次字符串交换就可以使两个字符串相等,返回true;否则返回false

思路 #

模拟 #

代码 #

模拟 #

class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        if (s1.length() != s2.length()) return false;
        int left = -1, right = -1;
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                if (left == -1) left = i;
                else if (right == -1) right = i;
                else return false;
            }
        }
        if (left == -1) return true;
        if (right == -1) return false;
        return s1.charAt(left) == s2.charAt(right) && s1.charAt(right) == s2.charAt(left);
    }
}

计数 #

致谢 #

宫水三叶