LeetCode 28 Implement strStr() 找到字串返回位置。,leetcodestrstr
題目:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
翻譯:
找到字串的子串位置,並返回。如果沒有則返回-1
思路:
通過最簡單的BF遍曆,如果不符合則指向下一個字元,最後如果長度等於子串長度,則返回位置。
代碼:
public static int strStr(String haystack, String needle) { if(haystack == null || needle == null) return 0; if(haystack.length() < needle.length()) return -1; int hlen = haystack.length(); int nlen = needle.length(); for(int i = 0 ; i <= hlen - nlen;i++) { int j = 0; for(;j < nlen;j++) { if(needle.charAt(j)!=haystack.charAt(i+j)) break; } if(j == nlen) return i; } return -1; }還有一種方法是KMP。雖說前些日子看了KMP,但讓自己動手寫起來還是難度有點大。
於是,又重新複習了一遍。貼上KMP的演算法。
public static void getNext(String str,int next[]){int j = 0;int k = -1;next[0] = -1;int len = str.length();while(j < len-1){if(k == -1 || str.charAt(k) == str.charAt(j)){j++;k++;next[j] = k;}else {k = next[k];}}}public static int KMP(String str,String temp){int i = 0;int j = 0;int slen = str.length();int tlen = temp.length();int []next = new int[tlen];getNext(temp, next);while(i < slen && j < tlen){if(str.charAt(i) == temp.charAt(j)){i++;j++;}else {if(next[j] == -1){i++;j = 0;}else {j = next[j];}}if(j == tlen)return i - j;}return -1;}/** * @param args */public static void main(String[] args) {// TODO 自動產生的方法存根String str = "ABC ABCDAB ABCDABCDABDE"; String pattern = "ABCDABD"; int i = KMP(str,pattern); System.out.println(i);}原理就是找到next的數組。然後在遍曆的時候如果匹配則返回,沒有匹配則跳指向next數組對應的位置,繼續掃描判斷。 還是部分細節的處理掌握不牢固。以後多看看。
後來查看大神的寫法,發現了一個不錯的。採用rolling hash。
連結:http://blog.csdn.net/linhuanmars/article/details/20276833
基本思想是用一個hashcode來表示一個字串,為了保證hash的唯一性,我們用比字元集大的素數為底,以這個素數的冪為基。舉例來說,字元集是小寫字母集,取素數29為底。比如字串“abacd",轉化為hashcode=1+2*29+1*29^2+3*29^3+4*29^4。然後是如何在前進一步的時候計算新的hashcode,比如匹配串是原串是”abacde“,匹配串長度為5,根據以上的方法計算”abacd“的hashcode=h,那麼下一步”bacde“的hashcode=h/29+5*29^4。這是一個constant的操作,所以檢測所有子串的時間複雜度只需要O(m+n-m)=O(n),也是一個線性演算法。
public String strStr(String haystack, String needle) { if(haystack==null || needle==null) return null; if(haystack.length()==0){ return needle.length()==0?"":null; } if(needle.length()==0) return haystack; if(haystack.length()<needle.length()) return null; int base = 29; long patternHash = 0; long tempBase = 1; for(int i=needle.length()-1; i>=0; i--){ patternHash += (int)needle.charAt(i)*tempBase; tempBase *= base; } long hayHash = 0; tempBase = 1; for(int i=needle.length()-1; i>=0; i--){ hayHash += (int)haystack.charAt(i)*tempBase; tempBase *= base; } tempBase /= base; if(hayHash == patternHash){ return haystack; } for(int i=needle.length(); i<haystack.length(); i++){ hayHash = (hayHash - (int)haystack.charAt(i-needle.length())*tempBase)*base+(int)haystack.charAt(i); if(hayHash == patternHash){ return haystack.substring(i-needle.length()+1); } } return null; }