当前位置:网站首页>Force buckle 1790 Can two strings be equal by performing string exchange only once

Force buckle 1790 Can two strings be equal by performing string exchange only once

2022-07-07 20:06:00 Tomorrowave

1790. Can performing only one string exchange make two strings equal

Give you two strings of equal length s1 and s2 . once String swapping The operation steps are as follows : Select two subscripts in a string ( It doesn't have to be different ), And exchange the characters corresponding to the two subscripts .

If the One of the strings perform At most one string exchange You can make two strings equal , return true ; otherwise , return false .

Example 1:

Input :s1 = “bank”, s2 = “kanb”
Output :true
explain : for example , In exchange for s2 The first and last characters in can get “bank”

Ideas :

Matching algorithm idea . string matching

Code section

class Solution:
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        s1,s2=list(s1),list(s2)
        if len(s1)!=len(s2):
            return False
        cnt=[]
        for i in range(len(s1)):
            if s1[i]!=s2[i] and len(cnt)<2 :
                cnt.append(i)
        if len(cnt)==2:
            s1[cnt[0]],s1[cnt[1]]= s1[cnt[1]],s1[cnt[0]]
        return s1==s2
原网站

版权声明
本文为[Tomorrowave]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071753356339.html