• 【算法】串匹配


    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;
        }
        
    }
  • 相关阅读:
    fastjson 简单使用 及其JSONObject使用
    HttpClient 的使用
    python操作excel xlwt (转)
    matplotlib 设置标题 xy标题等
    matplotlib 饼状图
    Mac下面 matplotlib 中文无法显示解决
    matplotlib 折线图
    matplotlib条形图
    matplotlib直方图
    python matplotlib配置
  • 原文地址:https://www.cnblogs.com/cuglkb/p/7823327.html
Copyright © 2020-2023  润新知