↓快轉到主要內容
  1. LeetCode/

LeetCode 521: Longest Uncommon Subsequence I

·1 分鐘· ·
LeetCode Easy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-25

  • 提交紀錄:Accepted(一次通過)

解題思路
#

如果 a == b,a 的任何子序列也都是 b 的子序列,答案 -1。否則比較長的那個字串整個就不會是另一個的子序列(比它長,或一樣長但不相同),答案是 max(len(a), len(b))。

我的解法
#

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        return -1 if a == b else max(len(a), len(b))

複雜度
#

時間 O(n)(比較字串),空間 O(1)。

要特別避免的錯誤
#

  • 一樣長但內容不同時,任一個字串整個都是答案。

面試口說整理
#

兩個字串相同時沒有答案,回傳 -1;不同時比較長的那個字串整個不可能是另一個的子序列,所以答案就是比較長的長度。

相關文章

LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 520: Detect Capital
·1 分鐘
LeetCode Easy String
LeetCode 520 解題筆記:合法的只有三種:全大寫、全小寫、只有第一個字母大寫
LeetCode 434: Number of Segments in a String
·1 分鐘
LeetCode Easy String
LeetCode 434 解題筆記:split() 不帶參數會忽略多餘的空白,切出來的數量就是答案
LeetCode 345: Reverse Vowels of a String
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 345 解題筆記:跟 LC 917 一樣的左右指針,只是條件換成「是不是母音」(大小寫都要算)
LeetCode 504: Base 7
·1 分鐘
LeetCode Easy Math String
LeetCode 504 解題筆記:對絕對值不斷取 % 7 和 // 7,最後加上負號並反轉;0 要特別處理
LeetCode 541: Reverse String II
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 541 解題筆記:每 2k 個為一段,反轉每段的前 k 個;最後一段不足 k 個時全部反轉,切片會自動處理