Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
题目要求
- 给定两个字符串,一个主串一个子串,查找子串在主串中的位置
- 返回第一个子串出现的下标
- 不是子串则返回-1,子串长度为0则返回0
解题思路
从头到尾遍历主串中的每一个字符,如果找到一个字符与子串的第一个字符相同,则继续比较主串下一个字符和子串的第二个字符相不相等,如果相等则继续比较。依此类推。
注意在逐个比较中会记录主串中下一个与子串第一个字符相同的位置,这样可以跳过一些不必要的比较。
时间复杂度O(mn),超过66%的java提交,代码如下:
class Solution {
public int strStr(String haystack, String needle) {
int result = -1,lastFirst = 0;
int hlen = haystack.length(),nlen = needle.length();
if(nlen==0) return 0;
if(hlen == 0) return -1;
char c,nfc=needle.charAt(0);
l1:for(int i = 0;i < hlen;i++){
if(i < lastFirst) i = lastFirst; // 更新起始的搜索值,可以跳过一些不必要的检测
c = haystack.charAt(i);
if(c==nfc){ // 找到第一个匹配的
lastFirst = i; // 记住匹配的第一个的位置
for(int j = 1;j < nlen;j++){
if(i+j >= hlen) return -1; // 左边超出,说明没有匹配
if(lastFirst<i&&haystack.charAt(i+j) == nfc) lastFirst = i+j;// 只找第一个
if(haystack.charAt(i+j)!=needle.charAt(j)) continue l1;
}
result = i;
return result;
}
}
return result;
}
}