[leetcode] 28. Implement strStr()

网友投稿 277 2022-11-14

[leetcode] 28. Implement strStr()

Description

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

分析

题目的意思是:实现一个strStr()函数,返回在haystack中首先出现needle字符串的索引。

这道题就是一个字符串匹配的问题,我这里是暴力解决的。当然这道题还有优化的KMP算法,我调了几遍没有ac,以后有机会补上KMP版本。

代码

class Solution {public: int strStr(string haystack, string needle) { if(needle.empty()){ return 0; } int m=haystack.length(); int n=needle.length(); for(int i=0;i<=m-n;i++){ bool flag=true; for(int j=0;j

参考文献

​​[编程题]implement-strstr​​​​[LeetCode] Implement strStr() 实现strStr()函数​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微雪电子mega64 mega128测试座介绍
下一篇:Elasticsearch入门与优化
相关文章

 发表评论

暂时没有评论,来抢沙发吧~