p28

LeetCode p28 Implement strStr() 题解

1.题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

题意:

输入两个字符串判断第一个字符串里面是否包含第二个字符串。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
public class Solution {
public int strStr(String haystack, String needle) {
int ans = -1;
int n = haystack.length();
int m = needle.length();
if (haystack.equals(needle) || needle.equals(""))
return 0;
if (m >= n)
return -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i + j == haystack.length())
return -1;
// System.out.println(i + "---" + j);
if (haystack.charAt(i + j) != needle.charAt(j))
break;
if (j == m - 1)
return i;

}
}
return ans;
}
}

4.一些总结: