每日一题——LeetCode1455.检查单词是否为句中其他单词的前缀

方法一 js函数slice()

 将字符串按空格符分割为单词数组,记searchWord的长度为n,分割每个单词的前n位看是否和searchWord匹配

var isPrefixOfWord = function(sentence, searchWord) {
    let res = sentence.split(" ")
    for(i = 0 ; i < res.length ; i++) {
        if (res[i].slice(0,searchWord.length) === searchWord) {
            return i + 1
        }
    }
    return -1
}

消耗时间和内存情况:

方法二 双指针:

来自leetcode官方题解
链接:1455.检查单词是否为句中其他单词的前缀

使用 start 记录单词的起始,end记录单词结尾的下一个位置。我们遍历字符串 sentence并不断地分割单词,对于区间[start,end) 对应的单词,判断它是否存在某一前缀等于 searchWord,如果存在直接返回该单词对应的下标 index;如果遍历完所有单词都不符合条件,返回 −1。

var isPrefixOfWord = function(sentence, searchWord) {
    let n = sentence.length, index = 1, start = 0, end = 0;
    while (start < n) {
        while (end < n && sentence[end] !== ' ') {
            end++;
        }
        if (isPrefix(sentence, start, end, searchWord)) {
            return index;
        }

        index++;
        end++;
        start = end;
    }
    return -1;
}

const isPrefix = (sentence, start, end, searchWord) => {
    for (let i = 0; i < searchWord.length; i++) {
        if (start + i >= end || sentence[start + i] !== searchWord[i]) {
            return false;
        }
    }
    return true;
};

消耗时间和内存情况:

相关推荐

  1. 每日 --- 反转字符串单词[力扣][Go]

    2024-02-18 22:40:01       22 阅读
  2. 【C++】每日 58 最后一个单词长度

    2024-02-18 22:40:01       18 阅读
  3. leetcode】反转字符串单词

    2024-02-18 22:40:01       22 阅读
  4. LeetCode 每日(Hard) Day 11||单调

    2024-02-18 22:40:01       35 阅读
  5. LeetCode每日单调栈 901股票价格跨度

    2024-02-18 22:40:01       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-18 22:40:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-18 22:40:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-18 22:40:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-18 22:40:01       20 阅读

热门阅读

  1. mysql时间处理问题

    2024-02-18 22:40:01       31 阅读
  2. Day08-别名-重定向-去重排序等

    2024-02-18 22:40:01       23 阅读
  3. Linux :sh、可执行文件,无法使用. / 安装执行

    2024-02-18 22:40:01       27 阅读
  4. Leetcode 6-10题

    2024-02-18 22:40:01       23 阅读
  5. 游戏开发速成入门

    2024-02-18 22:40:01       28 阅读
  6. C#面:简述重载

    2024-02-18 22:40:01       31 阅读
  7. re:从0开始的CSS之旅 20. 渐变(暂完结撒花)

    2024-02-18 22:40:01       26 阅读
  8. P1025 [NOIP2001 提高组] 数的划分

    2024-02-18 22:40:01       37 阅读