zoukankan      html  css  js  c++  java
  • LeetCode 10 Regular Expression Matching(字符串匹配)

     
    '.' Matches any single character.匹配任何单字符
    '*' Matches zero or more of the preceding element.匹配0个或者多个前置元素
    
    采用动态规划方法
    public boolean isMatch(String s, String p)
    1, If p.charAt(j) == s.charAt(i) :  dp[i][j] = dp[i-1][j-1];
    进行下一层的计算
    2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
    字符为’.'时也进行下一层dp[i-1][i-1]运算
    3, If p.charAt(j) == '*’: 
    当字符为’*’时,需要进行分类考虑
       here are two sub conditions:
    
       1   if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2]  //in this case, a* only counts as empty
    当’*’前面的一个字符和匹配串字符不相同时,则从模式串删去*以及其前面一个字符
    
        2   if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.’:
    
                        dp[i][j] = dp[i-1][j]    //in this case, a* counts as multiple a 
    
                        or dp[i][j] = dp[i][j-1]   // in this case, a* counts as single a
    
                        or dp[i][j] = dp[i][j-2]   // in this case, a* counts as empty


    参考代码:
    package leetcode;
    
    /***
     * 
     * @author pengfei_zheng
     * 字符串匹配问题
     */
    public class Solution10{
        public boolean isMatch(String s, String p) {
            return match(s,p,0,0);
        }
        private boolean match(String s,String p,int i,int j){//其中i,j分别为开始下标
            if(j==p.length())//匹配至长度相同
                return i==s.length();
            if(j==p.length()-1 || p.charAt(j+1)!='*'){//匹配至下一个字符不为'*'
                if(i==s.length() || s.charAt(i)!=p.charAt(j) && p.charAt(j)!='.')//不相等或者不等于'.'
                    return false;
                else 
                    return match(s,p,i+1,j+1);
            }
            while(i<s.length() && (s.charAt(i)==p.charAt(j) || p.charAt(j)=='.')){//相等或者等于'.'
                if(match(s,p,i,j+2))
                    return true;
                i++;
            }
            return match(s,p,i,j+2);
        }
    }
    
    
    
     
  • 相关阅读:
    Java Mysql连接池配置和案例分析--超时异常和处理
    springmvc学习笔记--Interceptor机制和实践
    Apache HttpClient使用之阻塞陷阱
    springmvc学习笔记--REST API的异常处理
    基于redis的排行榜设计和实现
    MySQL修改root密码的方法总结
    Ubuntu 16.04下安装golang
    锁优化的手段总结
    Java内存溢出问题总结
    GC日志时间分析
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/6498538.html
Copyright © 2011-2022 走看看