LeetCode Brush Questions 1790. Can two strings be equal to one string exchange?

LeetCode Brush Questions 1790. Can two strings be equal to one string exchange?

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Title :
    you two strings of equal length s1and s2. The steps of a string exchange operation are as follows: select two subscripts in a string (not necessarily different), and exchange the characters corresponding to the two subscripts.
    If one of the strings is exchanged at most once to make the two strings equal, return true; otherwise, return false.
  • Example :
示例 1 :
输入:s1 = "bank", s2 = "kanb"
输出:true
解释:例如,交换 s2 中的第一个和最后一个字符可以得到 "bank"
示例 2 :
输入:s1 = "attack", s2 = "defend"
输出:false
解释:一次字符串交换无法使两个字符串相等
示例 3 :
输入:s1 = "kelb", s2 = "kelb"
输出:true
解释:两个字符串已经相等,所以不需要进行字符串交换
示例 4 :
输入:s1 = "abcd", s2 = "dcba"
输出:false
  • Tips :
  • 1 <= s1.length, s2.length <= 100
  • s1.length == s2.length
  • s1And s2lowercase letters in English only
  • Code 1:
class Solution:
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        if len(s1) != len(s2):
            return False
        count = 0
        for i in range(len(s1)):
            if s1[i] != s2[i]:
                if s1[i] in s2[:]:
                    count += 1
                if s1[i] not in s2[:]:
                    return False
            if count > 2:
                return False
        return True
# 执行用时:44 ms, 在所有 Python3 提交中击败了37.11%的用户
# 内存消耗:14.8 MB, 在所有 Python3 提交中击败了87.05%的用户
  • Algorithm description:
    • Determine whether the lengths of two strings are equal;
    • Traverse two strings, if you encounter different characters, judge whether they appear in another string, and count;
    • If it does not exist in another string, it returns False;
    • If the number of different characters is greater than 2, return False;
    • Finally returns True.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/114889779
Recommended