程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 更多關於編程 >> java模式匹配之蠻力匹配

java模式匹配之蠻力匹配

編輯:更多關於編程

       這篇文章主要介紹了java模式匹配之蠻力匹配的相關資料和代碼,需要的朋友可以參考下

      java模式匹配之蠻力匹配

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 /** * 模式匹配之蠻力匹配 */ package javay.util;   /** * Pattern Match Brute-Force * @author DBJ */ public class PMBF {   /** * Pattern Match Brute-Force * @param target 目標串 * @param pattern 模式串 * @return 模式串在目標串中第一次出現的位置 */ public static int patternMatch(String target, String pattern) { int targetLength = target.length(); int patternLength = pattern.length(); int idxTgt = 0; // 目標串中字符的位置 int idxPtn = 0; // 模式串中字符的位置   int index = 0; // 保存與模式串匹配ing的起始字符的位置 while(idxTgt < targetLength && idxPtn < patternLength) { //找到一個匹配的字符 if(target.charAt(idxTgt) == pattern.charAt(idxPtn)) { // 如果相等,則繼續對字符進行後續的比較 idxTgt ++; idxPtn ++; } else { // 否則目標串從第二個字符開始與模式串的第一個字符重新比較 index ++; idxPtn = 0; idxTgt = index; } } // 匹配到一個,輸出結果 if(idxPtn == patternLength) { //說明匹配成功 return index; } else { return -1; } } }

      使用示例:

      ?

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 static int indexOf(char[] source,char[] target) { char first = target[0]; int max = (source.length - target.length); for (int i = 0; i <= max; i++) { /* Look for first character. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + target.length - 1; for (int k = 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* Found whole string. */ return i ; } } } return -1; }

      以上所述就是本文的全部內容了,希望大家能夠喜歡。

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved