LeetCode刷題Easy篇實現java裡面的indexOf方法
阿新 • • 發佈:2018-12-21
題目
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)); } }