28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
返回在haystack中第一次出现的needle的索引,如果不存在就返回-1。
思路:
方法一:
暴力解决,从左到右遍历haystack每一个元素,查找needle第一个字符出现的位置,然后截取和needle等长的子串,比较二者是否相等,相等则找到,不等继续遍历,如果到最后还没有找到,返回-1,此法效率低。
1 | //You are here! Your runtime beats 2.39% of cpp submissions. |
方法二:
利用KMP算法,通过求next数组,完成子串和目标串的匹配,KMP算法详解。
1 | //You are here! Your runtime beats 13.13% of cpp submissions. |
方法三:
利用C++的string中封装的find方法,find方法详解。
1 | //You are here! Your runtime beats 57.50% of cpp submissions. |
Java Code:
1 | //性能好,须记住Java String中常用的API |
1 | class Solution { |