LeetCode 392.判断子序列

明天有网易的笔试,去牛客看了下网易的笔试真题,第一道就是这个题,做了一下

 

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

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

 

第一种方法遍历t,但是效率很低,只超过了百分之5哈哈

var isSubsequence = function(s, t) {
    let i = 0; //t的索引
    let j = 0; //s的索引
    for(i;i<t.length;i++){
        console.log(s[j],t[i])
        if(s[j] === t[i]){
            j++;
        }
    }
    if(s.length === j){
        return true;
    }else {
        return false;
    }
};

第二种方法遍历s,通过indexOf来判断,效率比较高

var isSubsequence = function(s, t){
    let i = 0; //t的索引
    let j = 0; //s的索引
    for(j;j<s.length;j++){
        i = t.indexOf(s[j],i)+1;
        if(i === 0){
            return false;
        } 
    }
    return true;
}

 

 

,去牛客看了下网易的笔试真题,第一道就是这个题,做了一下 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 第一种方法遍历t,但是效率很低,只超过了百分之5哈哈
[, Qù niú kè kànle xià wǎngyì de bǐshì zhēntí, dì yī dào jiùshì zhège tí, zuòle yīxià gěi dìng zìfú chuàn s hé t, pànduàn s shìfǒu wèi t de zǐ xùliè. Zìfú chuàn de yīgè zǐ xùliè shì yuánshǐ zìfú chuàn shānchú yīxiē (yě kěyǐ bù shānchú) zìfú ér bù gǎibiàn shèngyú zìfú xiāngduì wèizhì xíngchéng de xīn zìfú chuàn.(Lìrú,"ace"shì"abcde"de yīgè zǐ xùliè, ér"aec"bùshì). Dì yī zhǒng fāngfǎ biànlì t, dànshì xiàolǜ hěn dī, zhǐ chāo guò liǎo bǎi fēn zhī 5 hāhā]
When I went to the Niu Jing, I saw the written question of Netease. The first thing is this question, I have done it.



The given strings S and T are determined if the S is a subsequence of T.

A subsequence of a string is the original string delete some (or not deleted) characters without changing the new string formed relative positions of the remaining characters. (For example, "ACE" is a subsequence of "abcde", and "AEC" is not).



The first method traversed T, but the efficiency is very low, only more than 5% of 5 haha
posted @ 2021-03-12 14:36  JMH0113  阅读(71)  评论(0)    收藏  举报