简体   繁体   中英

Can someone explain me this leetcode string manipulation question?

I just started doing some leetcode questions, and quite not sure why in this problem, we considering a case when 2 words are equal. This is a problem statement:

Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad" And this is a solution

def buddyStrings(self, A, B):
        if len(A) != len(B): return False
        if A == B and len(set(A)) < len(A): return True
        dif = [(a, b) for a, b in zip(A, B) if a != b]
        return len(dif) == 2 and dif[0] == dif[1][::-1]

I cant why we consider second if condition and how this list comprehension workd in 3 if. I will appreciate any help.

Here are the checks:

def buddyStrings(self, A, B):
    if len(A) != len(B): return False  # can't be true if lengths not equal
    if A == B and len(set(A)) < len(A): return True  # if same letter appears twice in word
    dif = [(a, b) for a, b in zip(A, B) if a != b]  # get letters that don't match
    return len(dif) == 2 and dif[0] == dif[1][::-1]  # if mismatch length is 2 and mismatch of first letter is reverse of mismatch of second letter
 dif = [(a, b) for a, b in zip(A, B) if a != b]

it finds all charachters that are not equal to each other in the same position. for ABCDE and FGCDE

dif = [('A','F'), ('B','G')]

I guess maybe this would be a bit simplified version:

class Solution:
    def buddyStrings(self, A, B):
        if len(A) != len(B):
            return False
        if A == B and len(set(A)) < len(A):
            return True
        diff = []
        for i in list(zip(A, B)):
            if i[0] != i[1]:
                diff.append(i)
        return len(diff) == 2 and diff[0] == diff[1][::-1]

  • for i in list(zip(A, B)) means for a pair in A and B.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM