zoukankan      html  css  js  c++  java
  • LeetCode之Regular Expression Matching

    【题目描述】

    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).
    
    The function prototype should be:
    bool isMatch(const char *s, const char *p)
    
    Some examples:
    isMatch("aa","a") → false
    isMatch("aa","aa") → true
    isMatch("aaa","aa") → false
    isMatch("aa", "a*") → true
    isMatch("aa", ".*") → true
    isMatch("ab", ".*") → true
    isMatch("aab", "c*a*b") → true

    【解决思路】

    大概可以运用动态规划的思想,将其分为几种情况进行迭代即可解决:

    1、当正则表达式为空时,只需要判断原字符是否为空即可。

    2、当都不为空时,需要逐字符判断即可,首先判断第一个字符是否相等,其次需要根据第二个字符是否为*分为两种情况:

      1)第二个字符为*,则需要判断判断*表示第一个字符出现0次或者1次的情况。

      2)第二个字符不为*,则判断直接判断第二个结果。

    【代码】

    public class Solution
    {
        /**
         * @param s 原始数据
         * @param p 正则表达式,仅支持*、.
         * @return
         */
        public boolean isMatch(String s, String p) {
            if(p.isEmpty()) return s.isEmpty();
            
            boolean first_match = (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'));
            
            if(p.length() >= 2 && p.charAt(1) == '*')
            {
                return isMatch(s, p.substring(2)) || (first_match && isMatch(s.substring(1), p));
            }
            else
            {
                return first_match && isMatch(s.substring(1), p.substring(1));
            }
        }
        
        public static void main(String[] args)
        {
            System.out.println(new Solution().isMatch("abcccc", "c*abc*d"));
        }
    }
  • 相关阅读:
    java语言基础--标识符、关键字
    #考研碎碎念#3
    #考研笔记#计算机之word问题
    #考研#计算机文化知识1(局域网及网络互联)
    #学习笔记#jsp
    #学习笔记#JSP数据交互
    考研随笔2
    考研随笔1
    几个人
    全局变量
  • 原文地址:https://www.cnblogs.com/woniu4/p/8327642.html
Copyright © 2011-2022 走看看