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);
        }
    }
    
    
    
     
  • 相关阅读:
    设计模式(十)——模板方法模式
    用imageROI来增加某范围的像素
    OpenCv练习
    字符串格式化(七)-format
    列表初始化
    设计模式(九)——适配器模式
    右值引用&&
    设计模式(八)——外观模式
    Confluence 6 企业环境或者网站托管的 Java 配置策略
    Confluence 6 管理应用服务器内存设置
  • 原文地址:https://www.cnblogs.com/zpfbuaa/p/6498538.html
Copyright © 2011-2022 走看看