zoukankan      html  css  js  c++  java
  • 通配符实现

    问题描述:?代表一个字符;*代表0到多个字符。

    问题思路:(回溯)

    1.在逐步访问s、p串的过程中,遇到“*”时,记录此时s、p串的索引;
    2.令“*”匹配s串的i(i = 0, 1, 2, 3...)个字符,判断两个字符串是否匹配;
    3.如果不匹配则回溯至1中记录的两个索引,重复2;
    4.直至s串的最后一个字符,判断是否完全匹配。

    代码实现:

    public class Wildcard {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String s = "text.xmla";
            String p = "te**t.*la*";
            System.out.println(match(s, p));
        }
    
        public static boolean match(String s, String p) {
            //i和j分别为两个数组的指针
            //字符相同或为?,则指针后移
            //如果p[j]='*',去重,记录*的位置,便于回溯,依次使*匹配 0、1、2、n个字符,
            //即匹配i个不成功时,j回溯到*的位置,匹配i+1个
            
            char[] sc = s.toCharArray();
            char[] pc = p.toCharArray();
            //两个指针
            int i=0 ,j =0;
            int slen = sc.length;
            int plen = pc.length;
            //上一个*的位置
            int last_star_p = 0;
            int last_star_s = 0;
            
            while(i < slen) {
                if(j < plen && (sc[i] == pc[j] || pc[j] == '?')) {
                    //字符相同或为?
                    i++;
                    j++;
                }else if(j < plen && pc[j] == '*') {
                    //字符为*,去重,记录回溯点last_star_p,依次匹配0-n个字符
                    while(j < plen && pc[j] == '*') {
                        last_star_p = j;
                        j++;
                    }
                    last_star_s = i;
                }else if(last_star_p < plen) {
                    //上边没有匹配上,则j回溯上一个*的位置last_star_p,使其匹配i+1个字符
                    j = last_star_p + 1;
                    last_star_s++;
                    i = last_star_s;
                } else {
                    return false;
                }
            }
            
            //p字符串尾部存在多个*号
            while(j < plen && pc[j] == '*') {
                j++;
            }
            
            return j == plen;
        }
    }

    输出:true

  • 相关阅读:
    Oracle数据库对表字段的操作命令
    解决eclipse中git中cannot open gituploadpack(无法打开Git上传包)问题
    C# 启动外部程序的几种方法
    php面试题及答案(转)
    每日知识(1)半结构化数据
    每日知识(2)云计算
    方法对象
    什么是MA移动平均线它的特点及应用
    My first testcase about C#&C++
    局部变量的角色
  • 原文地址:https://www.cnblogs.com/shuimuzhushui/p/12876550.html
Copyright © 2011-2022 走看看