Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
题目要求求字符串needle第一次在haystack中出现的位置
------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) {
return 0;
}
if (haystack.length() == 0) {
return -1;
}
int result = -1;
point:
for (int index = 0; index <= haystack.length() - needle.length(); index++){
for(int i = 0; i < needle.length(); i++) {
if (haystack.charAt(index + i) != needle.charAt(i)){
break;
}
if (i == needle.length() - 1) {
result = index;
break point;
}
}
}
return result;
}
}