字符串序列判定/最后一个有效字符(知识点:双指针)
方法1:
// 暴力 O(n^2)
function vaildStr(s, l) {
if (!s) return true;
const hash = {};
const lLen = l.length, sLen = s.length;
let preIndex = 0;
for (let i = 0; i < sLen; i++) {
hash[s[i]] = i;
}
let start = 0;
while (start < lLen && l[start] !== s[0]) {
start++;
}
let end = start + 1;
while (end < lLen) {
if (preIndex + 1 === hash[l[end]]) {
preIndex = hash[l[end]];
}
end++;
}
if (preIndex === sLen - 1) {
return preIndex;
}
return -1;
}
console.log(vaildStr('asm', 'asm'))
方法2
function vaildStr(s, l) {
const sLen = s.length, lLen = l.length;
let i = 0, j = 0;
while (i < sLen && j < lLen) {
if (s[i] === l[j]) {
i++;
if (i === sLen) {
return j;
}
}
j++;
}
return -1;
}