leetcode题目:https://leetcode-cn.com/problems/is-subsequence/
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
示例 1:
输入:s = "abc", t = "ahbgdc"
输出:true
示例 2:
输入:s = "axc", t = "ahbgdc"
输出:false
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
采用双指针,
var isSubsequence = function (s, t) {
let slen = s.length
let tlen = t.length
let i = 0,
j = 0;
while (i < slen && j < tlen) {
if (s[i] == t[j]) {
i++
}
j++
}
return i == slen
};
//此代码是将上面的代码进行优化,执行用时和内存消耗,都优化了
var isSubsequence = function (s, t) {
let slen = s.length
let tlen = t.length
if(slen==0)return true
let i = 0,
j = 0;
while (i < slen && j < tlen) {
if (s[i] == t[j]) i++
j++
}
return i == slen
};