简体   繁体   English

有人可以向我解释这个 leetcode 字符串操作问题吗?

[英]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.我刚开始做一些 leetcode 问题,并不确定为什么在这个问题中,我们考虑了 2 个单词相等的情况。 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.给定两个小写字母字符串 A 和 B,如果可以交换 A 中的两个字母使结果等于 B,则返回 true,否则返回 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].交换字母定义为采用两个索引 i 和 j(0 索引),使得 i != j 并交换 A[i] 和 A[j] 处的字符。 For example, swapping at indices 0 and 2 in "abcd" results in "cbad" And this is a solution例如,在“abcd”中的索引 0 和 2 处交换导致“cbad”这是一个解决方案

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.我不明白为什么我们考虑第二个 if 条件以及这个列表理解如何在 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对于 ABCDE 和 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. for i in list(zip(A, B))表示 A 和 B 中的一对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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