zoukankan      html  css  js  c++  java
  • [eetcode 10]Regular Expression Matching

    1 题目:

    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

    2 思路:

    好吧,这题我开始一个一个比较真是跪了,没有用递归,考虑各种情况,各种if-else,发现还是无法考虑所有情况。看别人写的,使用递归写的,思路很清楚。

    https://leetcode.com/discuss/32424/clean-java-solution

    看那个c++的,想转为java,真是跪了,c++用''表示字符串结束,而java字符串是数组,没有这个一说,各种越界加超时。

    https://leetcode.com/discuss/9405/the-shortest-ac-code

    3 代码:

        public boolean isMatch(String s, String p) {
            if (p.isEmpty()) {
                return s.isEmpty();
            }
    
            if (p.length() == 1 || p.charAt(1) != '*') {
                if (s.isEmpty() || (p.charAt(0) != '.' && p.charAt(0) != s.charAt(0))) {
                    return false;
                } else {
                    return isMatch(s.substring(1), p.substring(1));
                }
            }
    
            //P.length() >=2 && p.charAt(1) == '*'
            //                       the first char is match
            while (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) {  
                if (isMatch(s, p.substring(2))) { 
                    return true;                     
                }
                //see if the next char of s is still match
                s = s.substring(1);
            }
            //first char not match  , make * to 0
            return isMatch(s, p.substring(2));
        }


  • 相关阅读:
    编程语言的简介
    ava 8 stream的详细用法
    Java 8 Steam 例子整理
    redis常用命令
    常用正则表达式
    保留一些常用文章
    tag的简单使用
    GitFlow详解教程
    Git基本命令和GitFlow工作流
    Redis 2.8.18 安装报错 error: jemalloc/jemalloc.h: No such file or directory
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4565666.html
Copyright © 2011-2022 走看看