1. 程式人生 > >leetcode_392. Is Subsequence 判斷s是否為t的子串

leetcode_392. Is Subsequence 判斷s是否為t的子串

題目:

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and tt is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"

 is a subsequence of "abcde" while "aec" is not).

Example 1:
s = "abc"t = "ahbgdc"

Return true.

Example 2:
s = "axc"t = "ahbgdc"

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?


題意:

給定字串t和字串s,判斷s是否為t的子串,子串的意思是,s中的元素都在t中出現,且s中各元素在t中的相對位置保持不變。

程式碼:

class Solution(object):
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        
        m = len(s)
        n = len(t)
        if m>n :
            return False
        else :
            pos = 0            #記錄t中檢索到的當前位置
            for k in range(m) :     #遍歷s
                i = pos                  #對s中每個元素,在t中從當前位置pos開始查詢
                while i < n :
                    if t[i] == s[k] :            #如果s的元素s[k]在t中,更新t 的當前位置pos,用於s的下一個元素的查詢
                        pos = i+1
                        break
                    else :                #否則,i自增,繼續找t中是否有元素s[k]
                        i += 1
                if k < m and i == n :          #如果t遍歷完,但是s沒有遍歷完,則s不在t中
                    return False
            
            return True           #如果s遍歷完,且t沒遍歷完或剛好遍歷完,返回True

筆記:

思想比較簡單,不知道演算法好壞。