欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java模式匹配之蠻力匹配

 更新時間:2015年05月28日 16:30:50   投稿:hebedich  
這篇文章主要介紹了java模式匹配之蠻力匹配的相關(guān)資料和代碼,需要的朋友可以參考下

java模式匹配之蠻力匹配

/**
 * 模式匹配之蠻力匹配
 */
package javay.util;
 
/**
 * Pattern Match Brute-Force
 * @author DBJ
 */
public class PMBF {
 
  /**
   * Pattern Match Brute-Force
   * @param target 目標(biāo)串
   * @param pattern 模式串
   * @return 模式串在目標(biāo)串中第一次出現(xiàn)的位置
   */
  public static int patternMatch(String target, String pattern) {
    int targetLength = target.length();
    int patternLength = pattern.length();
    int idxTgt = 0; // 目標(biāo)串中字符的位置
    int idxPtn = 0; // 模式串中字符的位置
 
    int index = 0; // 保存與模式串匹配ing的起始字符的位置
    while(idxTgt < targetLength && idxPtn < patternLength) {
      //找到一個匹配的字符
      if(target.charAt(idxTgt) == pattern.charAt(idxPtn)) {
        // 如果相等,則繼續(xù)對字符進行后續(xù)的比較
        idxTgt ++;
        idxPtn ++;
      } else {
        // 否則目標(biāo)串從第二個字符開始與模式串的第一個字符重新比較
        index ++;
        idxPtn = 0;
        idxTgt = index;
      }
    }
    // 匹配到一個,輸出結(jié)果
    if(idxPtn == patternLength) {
      //說明匹配成功
      return index;
    } else {
      return -1;
    }
  }
}

使用示例:

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;
  }

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

相關(guān)文章

最新評論