Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
Tips:当输入文空字符串的时候应该返回0
package cn.edu.csu;
public class ImplementStrStrSolution {
public int strStr(String haystack, String needle) {
/**
* 朴素的字符串匹配
* 依次选取源串中的子串进行匹配
*/
int nlLen = needle.length();
int hsLen = haystack.length();
if (nlLen > hsLen) {
return -1;
}
if (nlLen == 0 || haystack.equals(needle)) {
return 0;
}
int result = -1;
for (int i = 0; i < hsLen - nlLen + 1; i++) {
//每次匹配不成功模块向后滑动一位
if (haystack.substring(i, i + nlLen).equals(needle)) {
result = i;
break;
}
}
return result;
}
}