Implement strStr() leetcode java

愛做飯的小瑩子發表於2014-08-07

題目

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 

題解:

其實我覺得這題。。為啥不給個更明確的解釋呢?

是不是如果不知道strStr()是幹嘛的就給直接掛了呢。。。

這道題就是讓你判斷,needle是不是haystack的子串,是的話就返回這個子串。

解題想法是,從haystack的第一個位置,開始逐個判斷是不是子串。如果整個子串都匹配了,那麼就返回,否則繼續往下挪位置。

注意要看haystack剩餘的長度跟needle比足不足夠多,不夠的話也就不用往後比了。

寫到這突然想起來這個不就是《資料結構》那本書裡面那個例子麼,這應該是最naive的解法,之後講的就是kmp解法,可以往後滑動的那種。。。

瞭解kmp演算法網上應該有很多教程,之前是看嚴蔚敏老師的視訊學習的,老師講的很細,拿著小紙片當指標一個一個指著給你講,很清楚。。。對我這種理解能力慢的人就恨受用了。。。

 

我這個就不是kmp了,就最naive的方法。

程式碼如下:

 

 1 public String strStr(String haystack, String needle) {
 2     if (needle.length() == 0)
 3         return haystack;
 4  
 5     for (int i = 0; i < haystack.length(); i++) {
 6         if (haystack.length() - i + 1 < needle.length())
 7             return null;
 8  
 9         int k = i;
10         int j = 0;
11  
12         while (j < needle.length() && k < haystack.length() && needle.charAt(j) == haystack.charAt(k)) {
13             j++;
14             k++;
15             if (j == needle.length())
16                 return haystack.substring(i);
17         }
18  
19     }
20     return null;
21 }

Reference:http://www.programcreek.com/2012/12/leetcode-implement-strstr-java/

 

1 public int strStr(String haystack, String needle) {
2    for (int i = 0; ; i++) {
3 for (int j = 0; ; j++) {
4 if (j == needle.length()) return i;
5 if (i + j == haystack.length()) return -1;
6 if (needle.charAt(j) != haystack.charAt(i + j)) break;
7 } }
8 }

 

相關文章