題目:
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 }
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 }
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 }