1.问题描述
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
2.求解
双指针
代码如下
/*
执行用时:2 ms, 在所有 Java 提交中击败了50.29% 的用户
内存消耗:37.2 MB, 在所有 Java 提交中击败了75.16% 的用户
*/
public int strStr(String haystack, String needle) {
int n = haystack.length(), l = needle.length();
if(l == 0){
return 0;
}
int pn = 0;
while(pn < n - l + 1){
while(pn < n - l + 1 && haystack.charAt(pn) != needle.charAt(0)){
pn++;
}
int curlen = 0, pl = 0;
while(pn < n && pl < l && haystack.charAt(pn) == needle.charAt(pl)){
++pl;
++pn;
++curlen;
}
if(curlen == l){
return pn - l;
}
pn = pn - curlen + 1;
}
return -1;
}
时间复杂度:最坏时间复杂度为 O((N−L)L),最优时间复杂度为 O(N)。
空间复杂度:O(1)。
ps:字符串的charAt方法效率高于subString方法,但是效率最高还是转换为字符数组,直接通过下标访问。
又尝试了下转换为char数组的效率,果然比charAt方法快了些,代码如下
/*
执行用时:1 ms, 在所有 Java 提交中击败了74.45% 的用户
内存消耗:38.7 MB, 在所有 Java 提交中击败了24.20% 的用户
*/
public int strStr(String haystack, String needle) {
char[] str1 = haystack.toCharArray();
char[] str2 = needle.toCharArray();
if(str2.length == 0){
return 0;
}
for(int i = 0 ;i < str1.length; i++){
int x = i;
int y = 0;
if(str1.length - i < str2.length){
return -1;
}
while(str1[x] == str2[y]){
if(y==str2.length-1){
return i;
}
x++;
y++;
}
}
return -1;
}