Skip to content

判断子序列-392 #89

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sl1673495 opened this issue Jun 20, 2020 · 1 comment
Open

判断子序列-392 #89

sl1673495 opened this issue Jun 20, 2020 · 1 comment

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 20, 2020

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

示例 1:
s = "abc", t = "ahbgdc"

返回 true.

示例 2:
s = "axc", t = "ahbgdc"

返回 false.

后续挑战 :

如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10 亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

致谢:

特别感谢 @pbrother  添加此问题并且创建所有测试用例。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/is-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

判断字符串 s 是否是字符串 t 的子序列,我们可以建立一个 i 指针指向「当前 s 已经在 t 中成功匹配的字符下标后一位」。之后开始遍历 t 字符串,每当在 t 中发现 i 指针指向的目标字符时,就可以把 i 往后前进一位。

  • 一旦i === t.length ,就代表 t 中的字符串全部按顺序在 s 中找到了,返回 true。
  • 当遍历 s 结束后,就返回 false,因为 i 此时并没有成功走 t 的最后一位。
/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */
let isSubsequence = function (s, t) {
    let sl = s.length
    if (!sl) {
        return true
    }

    let i = 0
    for (let j = 0; j < t.length; j++) {
        let target = s[i]
        let cur = t[j]
        if (cur === target) {
            i++
            if (i === sl) {
                return true
            }
        }
    }

    return false
};
@dusheng0927
Copy link

有两处地方的字符s和t写反了,
一旦i === s.length ,就代表 s中的字符串全部按顺序在 t中找到了,返回 true。
当遍历 t 结束后,就返回 false,因为 i 此时并没有成功走s 的最后一位。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants