鱼C论坛

 找回密码
 立即注册
查看: 899|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】392. Is Subsequence 判断子序列 #Easy #Python

[复制链接]
发表于 2023-5-23 14:46:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 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?

  1. class Solution(object):
  2.     def isSubsequence(self, s, t):
  3.         """
  4.         :type s: str
  5.         :type t: str
  6.         :rtype: bool
  7.         """
复制代码


Judy
python
  1. class Solution(object):
  2.     def isSubsequence(self, s, t):
  3.         """
  4.         :type s: str
  5.         :type t: str
  6.         :rtype: bool
  7.         """

  8.         j = 0
  9.         for x in s:
  10.             idx = t[j:].find(x)
  11.             if idx == -1:
  12.                 return False
  13.             j += idx + 1  
  14.         
  15.         return True
复制代码


Gray
c++ better version?!
  1. class Solution {
  2. public:
  3.     bool isSubsequence(string s, string t) {
  4.         if(s == "") return true;
  5.         if(t == "") return false;
  6.         int index = 0;
  7.         for(int i = 0; i < t.size(); i++){
  8.            if(s[index]==t[i]){
  9.                index++;
  10.            }
  11.            if(index==s.size()){
  12.                return true;
  13.            }
  14.         }
  15.         return false;
  16.     }
  17. };
复制代码


本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-28 20:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表