当前位置:网站首页>Implementation of leetcode question brushing str ()
Implementation of leetcode question brushing str ()
2022-04-23 06:53:00 【zjLOVEcyj】
Realization strStr() function .
Here are two strings haystack and needle , Please come in haystack Find in string needle The first place the string appears ( Subscript from 0 Start ). If it doesn't exist , Then return to -1 .
explain :
When needle When it's an empty string , What value should we return ? This is a good question in an interview .
For this question , When needle When it's an empty string, we should return 0 . This is related to C Linguistic strstr() as well as Java Of indexOf() The definition matches .
Example 1:
Input :haystack = “hello”, needle = “ll”
Output :2
Example 2:
Input :haystack = “aaaaa”, needle = “bba”
Output :-1
Example 3:
Input :haystack = “”, needle = “”
Output :0
Tips :
1 <= haystack.length, needle.length <= 104
haystack and needle It only consists of lowercase English characters
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/implement-strstr
var strStr = function(haystack, needle) {
need_length = needle.length
if (need_length === 0) return 0
if (need_length > haystack.lenght) return -1
let start = 0, end = 0
for (let k in haystack) {
k = parseInt(k)
start = k
end = k + need_length
if (haystack.slice(start, end) == needle) {
return start
}
}
return -1
}
let haystack = "", needle = ""
res = strStr(haystack, needle)
console.log(res);
版权声明
本文为[zjLOVEcyj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555334108.html
边栏推荐
猜你喜欢
随机推荐
Binary sum of leetcode questions
Promise(一)
百度地图案例-修改地图样式
window环境下使用小皮面板安装redis
CentOS8搭建PHP8.0.3运行环境
常用网站汇总
The time format is incorrect, and an error is reported when running the SQL file
js中的作用域与作用域链
Typescript (top)
阅读笔记:Secure Federated Matrix Factorization
js查找字符串中出现了三次的字符
Each traversal usage of tp6
TP6 的 each 遍历用法
端口占用1
.Net Core 下使用 Quartz —— 【4】作业和触发器之作业属性和异常
el-cascader和el-select点击别处让下拉框消失
freeCodeCamp----prob_calculator练习
ASP.NET CORE配置选项(下篇)
Concurrent optimization request
postMan 传参总结