本來是一個很簡單的問題,大神用五行代碼搞定,我卻要用四十行代碼,不過正好實現下KMP演算法,也是一種學習。
題目如下:
其實就是一個字串匹配的問題,匹配到哪,就輸出哪裡的下標,否則就輸出-1.看到這個題目的時候我一下子就想到了KMP演算法,本來以為是省時省力的,沒想到運算起來還是蠻慢的。Java實現KMP演算法求解如下:
//求NEXT數組public int[] makeNext(String P) { int q,k; int[] next = new int[P.length()]; next[0] = 0; for (q = 1,k = 0; q < P.length(); ++q) { while(k > 0 && P.charAt(q) != P.charAt(k)) k = next[k-1]; if (P.charAt(q) == P.charAt(k)) k++; next[q] = k; } return next; }//返回每次移動的值public int get_step(String haystack, String needle,int next[],int count){if(haystack.substring(count, needle.length()+count).equals(needle)) return -1;for(int i = needle.length();i>0;i--){if(haystack.substring(count, i+count).equals(needle.substring(0, i)) )return needle.substring(0, i).length()-next[i-1];}return 1;}//主函數,輸入兩個字串,返回匹配的第一個下標public int strStr(String haystack, String needle) {if(haystack.equals("")&&needle.equals("")) return 0; if(needle.equals("")) return 0; if(haystack.length()<needle.length()) return -1;int count=0,step =0;;int[] next = makeNext(needle);while (count<=haystack.length()-needle.length()){step = get_step(haystack, needle, next,count);if(step!=-1)count+=step;elsereturn count;}return -1; }