首页 > 其他 > 详细

Leetcode-Implement strStr()

时间:2014-11-29 08:51:07      阅读:244      评论:0      收藏:0      [点我收藏+]

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()

原文:http://www.cnblogs.com/lishiblog/p/4129980.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!