首页 > 代码库 > Leetcode-Implement strStr()
Leetcode-Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char *
or String
, please click the reload button to reset your code definition.
Solution:
1 public class Solution { 2 public int strStr(String haystack, String needle) { 3 if (haystack.length()<needle.length()) return -1; 4 if (needle.length()==0) return 0; 5 int len1 = haystack.length(); 6 int len2 = needle.length(); 7 for (int i=0;i<=len1-len2;i++) 8 if (compare(haystack,i,needle)) 9 return i;10 11 return -1;12 }13 14 public boolean compare(String haystack, int start, String needle){15 for (int i=0;i<needle.length();i++){ 16 char c1 = haystack.charAt(start+i);17 char c2 = needle.charAt(i);18 if (c1!=c2) return false;19 }20 return true;21 }22 23 24 }
NOTE: Seems that we can use KMP algorithm. PRACTICE IT!
Leetcode-Implement strStr()
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。