📅  最后修改于: 2023-12-03 15:28:43.529000             🧑  作者: Mango
给定一个字符串s和一个字符串t,判断s是否为t的子序列。
你可以按任意顺序删除s中的字符,但不能改变其顺序。例如,s = "abc"是t = "ahbgdc"的子序列,而s = "axc"不是t = "ahbgdc"的子序列。
输入:s = "abc", t = "ahbgdc" 输出:true
输入:s = "axc", t = "ahbgdc" 输出:false
可以使用双指针的方法来判断是否为子序列。使用两个指针i和j,分别指向s和t的开头,逐一匹配字符,如果s[i] = t[j],则i和j都向后移动一位;否则,只移动j。最终,如果i移动完毕,则说明s为t的子序列。
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)
class Solution {
public:
bool isSubsequence(string s, string t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s[i] == t[j]) {
i++;
}
j++;
}
return i == s.length();
}
};
class Solution {
public boolean isSubsequence(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
i++;
}
j++;
}
return i == s.length();
}
}
var isSubsequence = function(s, t) {
var i = 0, j = 0;
while (i < s.length && j < t.length) {
if (s[i] === t[j]) {
i++;
}
j++;
}
return i === s.length;
};
class Solution {
public:
bool isSubsequence(string s, string t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s[i] == t[j]) {
i++;
}
j++;
}
return i == s.length();
}
};