【Leetcode】java實現KMP演算法__演算法

來源:互聯網
上載者:User

本來是一個很簡單的問題,大神用五行代碼搞定,我卻要用四十行代碼,不過正好實現下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;    }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.