题目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解读:給字符串haystack和字符串needle,找到haystack中第一次出现needle的位置下标并返回。
代码:
class Solution {
public int strStr(String haystack, String needle) {
int len_1 = haystack.length();
int len_2 = needle.length();
if(len_2 == 0) return 0;
if(len_1<len_2) return -1;
for(int i = 0; i < len_1; i++) {
if(i + len_2 -1 >= len_1)
return -1;
else {
String temp = haystack.substring(i, i+len_2);
if(needle.equals(temp)) return i;
}
}
return -1;
}
}