题目
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
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().
我的尝试
本来打算在线性时间实现,但是需要KMP算法实现,KMP算法研究过思路,但是写出来目前不具备能力,先考虑非线性的实现吧,毕竟题目没有要求必需线性时间。
package com.puhui.flowplatform;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public static int findNeedle(String haystack,String needle) {
if (needle.equalsIgnoreCase("")){
return 0;
}
if (haystack.equalsIgnoreCase("")){
return -1;
}
int count=0;
for(int i=0,j=0;i<haystack.length()&&j<needle.length();i++){
//相等与否i都移动,j相同才移动,如何计算整个匹配?
if(haystack.charAt(i)==needle.charAt(j)){
count++;
j++;
}
else{
count=0;
}
if (count==needle.length()){
return i-count+1;
}
}
return -1;
}
public static void main(String[] args){
String hayStack="mississippi";
String needle="issip";
System.out.println(findNeedle(hayStack,needle));
}
}
写完之后,自认为完美,但是其实我忽略了一个重要的问题,我的hello中寻找ll这个case测试通过,但是在leetcode中提交没有通过,因为忽略了指针回溯的问题。比如mississippi中寻找issip,这个时候我i的循环已经过了第二个匹配的开始,i指针不能一直增加,如果部分匹配前缀的情况出现,那么j=0,i=i-count(此处不需要加1,因为for循环会自动加1),count=0,重新计数
修改后的代码如下,leetcode已经接受,就是时间复杂度有点高:
package com.puhui.flowplatform;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public static int findNeedle(String haystack,String needle) {
if (needle.equalsIgnoreCase("")){
return 0;
}
if (haystack.equalsIgnoreCase("")){
return -1;
}
int count=0;
int j=0;
for(int i=0;i<haystack.length()&&j<needle.length();i++){
//相等与否i都移动(错误的,i不同时移动,相同时需要考虑回溯),j相同才移动,如何计算整个匹配,引入count计数
if(haystack.charAt(i)==needle.charAt(j)){
count++;
j++;
}
else{
if(count!=0){
//发生过部分前缀匹配,计数清零,指针回溯,注意i在for循环加1了已经,所以这个回溯不需要加1
i=i-count;
j=0;
count=0;
}
}
if (count==needle.length()){
return i-count+1;
}
}
return -1;
}
public static void main(String[] args){
String hayStack="mississippi";
String needle="pi";
System.out.println(findNeedle(hayStack,needle));
}
}