標籤:leetcode java implement strstr
題目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
題意:
實現strStr()
返回needle在haystack中第一次出現的位置,如果haystack中不存在needle,返回-1.
演算法分析:
方法一:
* in Java, there is an API function name indexof(),
* it returns index within this string of the first occurrence of the specifiedsubstring.
方法二:
* 最native的做法
* 解題想法是,從haystack的第一個位置,開始逐個判斷是不是子串。如果整個子串都匹配了,那麼就返回,否則繼續往下挪位置。
* 注意要看haystack剩餘的長度跟needle比足不足夠多,不夠的話也就不用往後比了。
方法三:
* 利用看毛片(KMP)演算法,但是對於一個easy難度的題,利用這麼費腦的演算法沒必要吧~~
* 有興趣的參考《從頭到尾徹底理解KMP》http://blog.csdn.net/v_july_v/article/details/7041827
* 代碼也在下面給出來。
AC代碼:
方法一:
//in Java, there is an API function name indexof(),//it returns index within this string of the first occurrence of the specifiedsubstring. public class Solution { public int strStr(String haystack, String needle) { int i; i=haystack.indexOf(needle); return i; }}
方法二:
/** * 最native的做法 * 解題想法是,從haystack的第一個位置,開始逐個判斷是不是子串。如果整個子串都匹配了,那麼就返回,否則繼續往下挪位置。 * 注意要看haystack剩餘的長度跟needle比足不足夠多,不夠的話也就不用往後比了。 */ public class Solution{ public int strStr(String haystack, String needle) { if(haystack==null || needle==null) return 0; if(needle.length() == 0) return 0; for(int i=0; i<haystack.length(); i++) { if(i + needle.length() > haystack.length()) return -1; int m = i; for(int j=0; j<needle.length(); j++) { if(needle.charAt(j)==haystack.charAt(m)) { if(j==needle.length()-1) return i; m++; } else { break; } } } return -1; }}
方法三:
public int strStr(String haystack, String needle) { if(haystack==null || needle==null) return 0; int h = haystack.length();int n = needle.length(); if (n > h)return -1;if (n == 0)return 0; int[] next = getNext(needle);int i = 0; while (i <= h - n) {int success = 1;for (int j = 0; j < n; j++) {if (needle.charAt(0) != haystack.charAt(i)) {success = 0;i++;break;} else if (needle.charAt(j) != haystack.charAt(i + j)) {success = 0;i = i + j - next[j - 1];break;}}if (success == 1)return i;} return -1;} //calculate KMP arraypublic int[] getNext(String needle) {int[] next = new int[needle.length()];next[0] = 0; for (int i = 1; i < needle.length(); i++) {int index = next[i - 1];while (index > 0 && needle.charAt(index) != needle.charAt(i)) {index = next[index - 1];} if (needle.charAt(index) == needle.charAt(i)) {next[i] = next[i - 1] + 1;} else {next[i] = 0;}} return next;}
著作權聲明:本文為博主原創文章,轉載註明出處
[LeetCode][Java] Implement strStr()