题目
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
进阶:
如果有大量输入的 S,称作 S1, S2, … , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
示例
输入:s = “abc”, t = “ahbgdc”
输出:true
输入:s = “axc”, t = “ahbgdc”
输出:false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
实现
方法1:python
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
flag=-1
i,j=0,0
if s=='':
return True
while (i<len(t) and j<len(s)):
if s[j]==t[i]:
i+=1
j+=1
else:
i+=1
if j==len(s):
flag=0
if flag==0:
return True
else:
return False
方法2:java
class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) {
return true;
}
// 记录下标
int cnt_s = 0, cnt_t = 0;
// 逐位比较
while (cnt_t < t.length()) {
if (s.charAt(cnt_s) == t.charAt(cnt_t)) {
System.out.println(s.charAt(cnt_s));
cnt_s++;
cnt_t++;
} else {
cnt_t++;
}
// s是t的字串
if (cnt_s == s.length()) {
return true;
}
}
return false;
}
}