Judie 发表于 2023-5-23 14:46:46

【朱迪的LeetCode刷题笔记】392. Is Subsequence 判断子序列 #Easy #Python

本帖最后由 Judie 于 2023-5-23 20:23 编辑

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false

Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s and t consist only of lowercase English letters.

Follow up:
Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

class Solution(object):
    def isSubsequence(self, s, t):
      """
      :type s: str
      :type t: str
      :rtype: bool
      """

Judy
python
class Solution(object):
    def isSubsequence(self, s, t):
      """
      :type s: str
      :type t: str
      :rtype: bool
      """

      j = 0
      for x in s:
            idx = t.find(x)
            if idx == -1:
                return False
            j += idx + 1
      
      return True

Gray
c++ better version?!
class Solution {
public:
    bool isSubsequence(string s, string t) {
      if(s == "") return true;
      if(t == "") return false;
      int index = 0;
      for(int i = 0; i < t.size(); i++){
         if(s==t){
               index++;
         }
         if(index==s.size()){
               return true;
         }
      }
      return false;
    }
};

页: [1]
查看完整版本: 【朱迪的LeetCode刷题笔记】392. Is Subsequence 判断子序列 #Easy #Python