簡體   English   中英

有人可以向我解釋這個 leetcode 字符串操作問題嗎?

[英]Can someone explain me this leetcode string manipulation question?

我剛開始做一些 leetcode 問題,並不確定為什么在這個問題中,我們考慮了 2 個單詞相等的情況。 這是一個問題陳述:

給定兩個小寫字母字符串 A 和 B,如果可以交換 A 中的兩個字母使結果等於 B,則返回 true,否則返回 false。

交換字母定義為采用兩個索引 i 和 j(0 索引),使得 i != j 並交換 A[i] 和 A[j] 處的字符。 例如,在“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]

我不明白為什么我們考慮第二個 if 條件以及這個列表理解如何在 3 if 中工作。 我將不勝感激任何幫助。

以下是檢查:

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]

它在同一位置找到所有彼此不相等的字符。 對於 ABCDE 和 FGCDE

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

我想也許這會是一個簡化版:

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))表示 A 和 B 中的一對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM