zoukankan      html  css  js  c++  java
  • 算法小记:暴力字符串查找

    一、字符串查找 

    给定一段长度为N的文本和一个长度为M的模式(pattern)字符串,在文本中找到一个和该模式相符的子字符串 

     

    二、暴力字符串查找 

    在文本中模式可能出现匹配的任何地方检察匹配是否存在 

     

    三、代码 

     

    1. /**  
    2.  * 暴力字符串查找  
    3.  *   
    4.  * @author pengcx  
    5.  *   
    6.  */   
    7. public class Violence {   
    8.    
    9.     public static void main(String[] args) {   
    10.         String txt = "adldgkclsldajdc";   
    11.         String pat = "gkc";   
    12.    
    13.         System.out.println(Violence.search(pat, txt));   
    14.         System.out.println(Violence.searchother(pat, txt));   
    15.     }   
    16.    
    17.    
    18.     /**  
    19.     * 使用暴力字符串查找方式,在txt中查找和pat匹配的子字符串  
    20.     *   
    21.     * @param pat  
    22.     *            匹配的模板字符串  
    23.     * @param txt  
    24.     *            查找的字符串  
    25.     * @return 模板字符串第一次出现的位置  
    26.     */   
    27.     public static int search(String pat, String txt) {   
    28.         int M = pat.length();   
    29.         int N = txt.length();   
    30.    
    31.         // 逐个位置匹配模式字符串   
    32.         for (int i = 0; i < N; i++) {   
    33.             int j;   
    34.             for (j = 0; j < M; j++) {   
    35.                 if (txt.charAt(i + j) != pat.charAt(j)) {   
    36.                     break;   
    37.                 }   
    38.             }   
    39.    
    40.             // 找到了匹配的字符串   
    41.             if (j == M) {   
    42.                 return i;   
    43.             }   
    44.         }   
    45.         return N;   
    46.     }   
    47.    
    48.    
    49.     /**  
    50.     * 使用暴力字符串查找方式的另外一种实现  
    51.     *   
    52.     * @param pat  
    53.     *            匹配的模板字符串  
    54.     * @param txt  
    55.     *            查找的字符串  
    56.     * @return 模板字符串第一次出现的位置  
    57.     */   
    58.     public static int searchother(String pat, String txt) {   
    59.         int M = pat.length();   
    60.         int N = txt.length();   
    61.         int i;   
    62.         int j;   
    63.    
    64.         // 逐个位置匹配模式字符串   
    65.         for (i = 0, j = 0; i < N && j < M; i++) {   
    66.             if (txt.charAt(i) == pat.charAt(j)) {   
    67.                 j++;   
    68.             } else {   
    69.                 i -= j;   
    70.                 j = 0;   
    71.             }   
    72.         }   
    73.    
    74.         // 找到了匹配的字符串   
    75.         if (j == M) {   
    76.             return i - M;   
    77.        } else {   
    78.             return N;   
    79.        }   
    80.     }   
    81. }  
  • 相关阅读:
    ubuntu装openssh-client和openssh-server
    路由器开源系统openwrt配置页面定制
    linux 串口接收
    SHA算法
    密码学Hash函数
    椭圆曲线加密
    ElGamal密码
    Diffie-Hellman密钥交换
    RSA加密
    公钥密码学
  • 原文地址:https://www.cnblogs.com/haichun/p/3510888.html
Copyright © 2011-2022 走看看