【leetcode刷题】T175-判断子序列
- 2019 年 10 月 4 日
- 筆記
【题目】
给定字符串 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.
【思路】
本题较为简单,直观来说,对于s中的每个字符,遍历是否依次在t中出现。
不太好说,看代码~~
【代码】
python版本
class Solution(object): def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return False j = 0 for si in s: while j < len(t): if si == t[j]: break j += 1 if j >= len(t): return False j += 1 return True
C++版本
class Solution { public: bool isSubsequence(string s, string t) { int j = 0; for(int i=0; i<s.size(); i++){ while(j < t.size()){ if(s[i] == t[j]) break; j++; } if(j >= t.size()) return false; j++; } return true; } };