392. Is Subsequence

Leetcode

https://leetcode.com/problems/is-subsequence/

題目

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

解答

  • 方法一

var isSubsequence = function(s, t) {
    let indexS = 0;
    let indexT = 0;
    while(indexS < s.length) {
        const char = s[indexS];
        const newIndex = t.indexOf(char, indexT);
        if(newIndex === -1) return false;
        // 從 t 的下個 index 開始找有沒有符合的 char
        indexT = newIndex + 1;
        indexS++;
    }
    return true;
};

Runtime: 64 ms, faster than 98.32% of JavaScript online submissions for Is Subsequence.

Memory Usage: 38.6 MB, less than 83.95% of JavaScript online submissions for Is Subsequence.

測資

let s = "abc", t = "ahbgdc"; // true
// s = "axc", t = "ahbgdc"; // false
// s = "aaaaaa", t="bbaaaa"; // false

console.log(isSubsequence(s, t))

Last updated

Was this helpful?