392.鉴定子序列(javascript)392.IsSubsequence
原创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
};
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
上一篇:直指Offer10-II.蛙跳台阶原因 下一篇:vue将函数封装,借用公共的方式