码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Implement strStr()

时间:2014-11-29 08:54:17      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   strong   on   

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

标签:style   blog   io   ar   color   sp   for   strong   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!