zoukankan      html  css  js  c++  java
  • 10. Regular Expression Matching (JAVA)

    Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

    '.' Matches any single character.
    '*' Matches zero or more of the preceding element.
    The matching should cover the entire input string (not partial).

    Note:

    s could be empty and contains only lowercase letters a-z.
    p could be empty and contains only lowercase letters a-z, and characters like . or *.
    Example 1:

    Input:
    s = "aa"
    p = "a"
    Output: false
    Explanation: "a" does not match the entire string "aa".
    Example 2:

    Input:
    s = "aa"
    p = "a*"
    Output: true
    Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
    Example 3:

    Input:
    s = "ab"
    p = ".*"
    Output: true
    Explanation: ".*" means "zero or more (*) of any character (.)".
    Example 4:

    Input:
    s = "aab"
    p = "c*a*b"
    Output: true
    Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
    Example 5:

    Input:
    s = "mississippi"
    p = "mis*is*p*."
    Output: false

    class Solution {
        public boolean isMatch(String s, String p) {
            return recur(s,p,0,0);
        }
        
        public boolean recur(String s, String p, int sPtr, int pPtr) {
            if(s.length() == sPtr && p.length() == pPtr) return true;
            if(p.length() == pPtr) return false;
            if(s.length() == sPtr){
                if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*') return recur(s,p,sPtr,pPtr+2);
                else return false;
            }
            
            if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*'){ //next bit is *
                if(recur(s,p,sPtr,pPtr+2)) return true; //* match 0 element
                else{
                    for(int i = 1; sPtr + i <= s.length() && (p.charAt(pPtr)==s.charAt(sPtr+i-1)|| p.charAt(pPtr)=='.'); i++){
                        if(recur(s,p,sPtr+i,pPtr+2)) return true; //* match i elements
                    }
                } 
            }
            else if(p.charAt(pPtr)=='.' || p.charAt(pPtr)==s.charAt(sPtr)) 
                return recur(s, p, sPtr+1, pPtr+1);
            
            return false;
        }
    }

    当当前字符之后的那个字符是*时,我们需要对当前字符做特别判断,所以没次递归中要判断p字符串的下一个字符是否是*

  • 相关阅读:
    struts2_文件上传和下载
    struts2_方法拦截器
    struts2_Action之间的重定向传参
    struts2_全局的拦截器,拦截用户非法登陆
    Hibernate入门心得
    struts2_异常页面处理
    设计师小法器:字体大管家
    IE6,IE7下设置body{overflow:hidden;}失效Bug【转】
    子层的margintop属性应用到父层上的解决方法
    jQuery CSS选择器nthchild
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10762082.html
Copyright © 2011-2022 走看看