1. 程式人生 > >【Leetcode_總結】 392. 判斷子序列 - python

【Leetcode_總結】 392. 判斷子序列 - python

Q:

給定字串 s 和 t ,判斷 s 是否為 t 的子序列。

你可以認為 s 和 t 中僅包含英文小寫字母。字串 t 可能會很長(長度 ~= 500,000),而 s 是個短字串(長度 <=100)。

字串的一個子序列是原始字串刪除一些(也可以不刪除)字元而不改變剩餘字元相對位置形成的新字串。(例如,"ace""abcde"的一個子序列,而"aec"不是)。

示例 1:
s = "abc"t

 = "ahbgdc"

返回 true.

示例 2:
s = "axc"t = "ahbgdc"

返回 false.


連結:https://leetcode-cn.com/problems/is-subsequence/description/

思路:首先這個題的標籤是動態規劃,那就試試動態規劃,思路很簡單,狀態矩陣儲存最長子串長度,遍歷到最後,如果長度等於那個短的,就是True ,顯然題目告知了時間的問題,然後超時了,那就暴力著來吧,如果相同res+1,就有了程式碼2,通過了,但是沒什麼效率,第一名的程式碼是3,思路也不錯

程式碼:

第一個動態規劃,超時。。。

class Solution:
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if not s:
            return True
        if not t:
            return False
        if s==t:
            return True
        m = len(s)
        n = len(t)
        res = [[0 for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if s[i] == t[j]:
                    res[i][j] = res[i-1][j-1]+1
                else:
                    res[i][j] = max(res[i][j-1], res[i-1][j])
        return res[-1][-1] == m
class Solution:
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if not s:
            return True
        if not t:
            return False
        if s==t:
            return True
        s = list(s)
        t = list(t)
        m = len(s)
        n = len(t)
        i = 0
        j = 0
        res = 0
        while i < m and j < n:
            if s[i] == t[j]:
                res += 1
                i+=1
            j+=1
        return res == m

沒想到find函式的效率這麼高。。。

class Solution:
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if not s:
          return True
        for i in s:
          res = t.find(i)
          if res == -1:
            return False
          else:
            t = t[res+1:]
        return True