题目
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路
就是一个找子串的函数。
先顺势扫描,寻找首字母的匹配项,之后利用subString函数看剩余串是否匹配,如果匹配则最终返回i;寻找下一个首字母匹配位置;直到循环结束。
代码
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0 && haystack.length() == 0) return 0;
if(haystack.length() == 0 || haystack.length() < needle.length()) return -1;
if(needle.length() == 0) return 0;
int strStr = -1;
int length = needle.length();
char firstOfNeedle = needle.charAt(0);
for(int i = 0; i < (haystack.length() - length + 1) ; ++ i){
if(firstOfNeedle == haystack.charAt(i)){
if(haystack.substring(i , i + length).equals(needle)) return i;
}
}
return strStr;
}
}