zoukankan      html  css  js  c++  java
  • 【算法】串匹配

    package com.lkb.demo.test;
    
    public class StringTest {
        
        public static void main(String[] args) {
            StringTest test = new StringTest();
            char[] src = {'c','d','d','c','d','c'};
            char[] target = {'c','d','c'};
            int index = test.getIndex(src, target);
            System.out.println(index);
            int index2 = test.getIndexByBF(src, target);
            System.out.println(index2);
        }
        
        /**
         * String.indexOf(String str)的原理
         * 串与串之间的比较
         * 1、先找子串的头在目标串中匹配的位置
         * 2、如果找到,再接着比较
         * 3、如果没找到,接着找,知道找遍主串
         * @param src
         * @param target
         * @return
         */
        public int getIndex(char[] src, char[] target){
            char begin = target[0]; //
            int index = -1;
            for(int i=0;i<src.length;i++){
                
                if(src[i] == begin){//找到头
                    int beginIndex = i;
                    int j = 0;
                    while( j < target.length && beginIndex < src.length){
                        if(src[beginIndex] == target[j]){
                            beginIndex++;
                            j++;
                        }
                        else 
                            break;
                    }
                    if(j == target.length)
                        return (index = i);
                }
            }        
            return index;
        }
        
        /**
         * Brute-Force 暴力匹配
         * 每个字符一一匹配
         * @param src
         * @param target
         * @return
         */
        public int getIndexByBF(char[] src, char[] target){
            int index = -1;
            for(int i=0;i<src.length;){
                int j;
                for(j=0;j<target.length;){
                    if (src[i] == target[j]) {//字符匹配
                        i++;
                        j++;
                    }else{
                        i++;
                        break;
                    }
                }
                if(j == target.length)
                    index = i - j;
            }
            
            return index;
        }
        
    }
  • 相关阅读:
    OC语言前期准备
    C语言指针
    C语言字符串
    C语言数组
    python语法
    shell脚本命令 运行python文件&python命令行运行python代码
    HTTP Status完整枚举
    CRON表达式
    mybatis-generator生成的mapper中的
    iOS事件的响应和传递机制
  • 原文地址:https://www.cnblogs.com/cuglkb/p/7823327.html
Copyright © 2011-2022 走看看