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

方法一 js函数slice()

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

javascript 复制代码
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。

javascript 复制代码
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;
};

消耗时间和内存情况:

相关推荐
chushiyunen10 分钟前
python中的内置属性 todo
开发语言·javascript·python
soso196834 分钟前
JavaScript性能调优实战案例
javascript
2301_8194143036 分钟前
C++与区块链智能合约
开发语言·c++·算法
Zaly.42 分钟前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
做怪小疯子1 小时前
蚂蚁暑期 319 笔试
算法·职场和发展
计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
啊哦呃咦唔鱼1 小时前
LeetCode hot100-73 矩阵置零
算法
阿贵---1 小时前
C++构建缓存加速
开发语言·c++·算法
Moment1 小时前
前端工程化 + AI 赋能,从需求到运维一条龙怎么搭 ❓❓❓
前端·javascript·面试
Joker Zxc2 小时前
【前端基础(Javascript部分)】6、用JavaScript的递归函数和for循环,计算斐波那契数列的第 n 项值
开发语言·前端·javascript