Leetcode 391, Is Subsequence
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 t. t 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.
本题的思路比较简答,设置一个计数器,在scan list t的过程中,每发现一个s里面的字母,计数器就+1。如果计数器等于s的长度,说明已经找到一个subsequence 等于s。
1 class Solution(object): 2 def isSubsequence(self, s, t): 3 """ 4 :type s: str 5 :type t: str 6 :rtype: bool 7 """ 8 if not s: 9 return True 10 i = 0 11 for c in t: 12 if c == s[i]: 13 i += 1 14 if i == len(s): 15 return True 16 17 return False
本题也可以用queue的思想,注意popleft() 和 collections.deque(s) 的使用。参考书影博客 http://bookshadow.com/weblog/2016/09/04/leetcode-is-subsequence/
1 class Solution(object): 2 def isSubsequence(self, s, t): 3 """ 4 :type s: str 5 :type t: str 6 :rtype: bool 7 """ 8 queue = collections.deque(s) 9 10 for x in t: 11 if not queue: 12 return True 13 if queue[0] == x: 14 queue.pop(0) 15 16 return not queue

浙公网安备 33010602011771号