Java實現演算法導論中樸素字串匹配演算法
阿新 • • 發佈:2019-01-09
樸素字串匹配演算法沿著主串滑動子串來迴圈匹配,演算法時間效能是O((n-m+1)m),n是主串長度,m是字串長度,結合演算法導論中來理解,具體程式碼參考:
執行結果:package cn.ansj; public class NavieStringMatcher { public static void main(String[] args) { String T = "歡迎訪問fjssharpsword部落格,致力於大資料應用解決方案提供!"; String P = "大資料應用解決方案"; NavieStringMatcher nsm = new NavieStringMatcher(); int index = nsm.stringMatcher(T, P); System.out.println("有效位移是: "+index); } /** * @author fjssharpsword * @param T 主字串 * @param P 模式字串 * @return s 有效位移 */ public int stringMatcher(String T, String P){ int iTLen = T.length(); int iPLen = P.length(); // 從主串開始比較 for(int i=0; i<iTLen; i++) { int k = i; // k指向主串下一個位置 for(int j=0; j<iPLen; j++) { if(T.charAt(k) != P.charAt(j)) { break; }else { k++;// 指向主串下一個位置 if(j == iPLen-1) { return i; } } } } return -1; // 匹配不成功,返回-1 } }
有效位移是: 23