程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

LeetCode-1790. Can a string exchange be performed only once to make two strings equal_ Python

編輯:Python
  • Give you two strings of equal length s1 and s2 . The steps of a string exchange operation 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 you perform at most one string exchange on one of the strings, you can make the 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”

Example 2:

Input :s1 = “attack”, s2 = “defend”
Output :false
explain : A string exchange cannot make two strings equal

Example 3:

Input :s1 = “kelb”, s2 = “kelb”
Output :true
explain : The two strings are equal , So there's no need for string swapping

Example 4:

Input :s1 = “abcd”, s2 = “dcba”
Output :false

Tips :

1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1 and s2 It's only made up of lowercase letters

Program code

class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
ans1 = 0
ans2 = []
ans3 = []
for i in range(len(s1)):
if s1[i] != s2[i]:
ans1 += 1
ans2.append(s1[i])
ans3.append(s2[i])
if ans1 == 3:
return False
if ans1 == 2:
if ans2[0] in ans3 and ans2[1] in ans3:
return True
return False

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved