栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

算法记录——27实现 strStr()

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法记录——27实现 strStr()

题目:

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。
输入:haystack = "hello", needle = "ll"
输出:2
输入:haystack = "aaaaa", needle = "bba"
输出:-1
输入:haystack = "", needle = ""
输出:0

暴力解题:


// @lc code=start

var strStr = function (haystack, needle) {
  if (!needle) return 0;
  if (haystack.includes(needle)) {
    for (let index = 0; index < haystack.length; index++) {
      const element = haystack[index];
      if (element == needle[0]) {
        let flag = true;
        for (let i = 0; i < needle.length; i++) {
          const item = needle[i];
          if (item != haystack[index + i]) {
            flag = false;
          }
        }
        if (flag) return index;
      }
    }
  } else {
    return -1;
  }
};
// @lc code=end


// @lc code=start

var strStr = function (haystack, needle) {
    return haystack.indexOf(needle)
};
// @lc code=end

我看题解还有个KMP算法但是我不会所以就先这样吧

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/717614.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号