`

LeetCode 10 - 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

两种方法,回溯和动态规划。

Solution 1:

Dynamic Programming.

public boolean isMatch(String s, String p) {
    int m = s.length(), n = p.length();
    if(n==0) return m==0;
    boolean[][] f = new boolean[m+1][n+1];
    f[0][0] = true;
    for(int j=2; j<=n; j++) {
        if(p.charAt(j-1)=='*') {
            f[0][j] = f[0][j-2];
        }
    }
    for(int i=1; i<=m; i++) {
        for(int j=1; j<=n; j++) {
            char cp = p.charAt(j-1);
            char cs = s.charAt(i-1);
            if(cp == '*') {
                char cp2 = p.charAt(j-2);
                if(cp2 == cs ||cp2 == '.') {
                    f[i][j] = f[i][j-2] || f[i-1][j];
                } else {
                    f[i][j] = f[i][j-2];
                }
            } else {
                if(cp == cs || cp == '.') {
                    f[i][j] = f[i-1][j-1];
                }
            }
        }
    }
    return f[m][n];
}

 

Solution 2:

Backtracking.

public boolean isMatch(String s, String p) {
    int sLen = s.length();
    int pLen = p.length();
    if(pLen == 0) {
        return sLen == 0;
    }
    char c = p.charAt(0);
    if(pLen == 1 || p.charAt(1) != '*') { //p is without *, i.e. ab
        if(sLen == 0 || (c != '.' && c != s.charAt(0))) {
            return false;
        } else {
            return isMatch(s.substring(1), p.substring(1));
        }
    } else { // p is with *, i.e. a*b
        int i=-1;
        while(i<sLen && (i<0 || c == '.' || c == s.charAt(i))) {
            if(isMatch(s.substring(i+1), p.substring(2))) {
                return true;
            }
            i++;
        }
    }
    return false;
}

又重构了下递归的代码:

public boolean isMatch(String s, String p) {
    int m = s.length(), n = p.length();
    if(n == 0) return m==0;
    char c = p.charAt(0);
    if(n==1 || p.charAt(1) != '*') { // p has no *
        if(m == 0 || s.charAt(0) != c && c != '.') return false;
        return isMatch(s.substring(1), p.substring(1));
    } else { // p has *
        int i = -1;
        do {
            if(isMatch(s.substring(++i), p.substring(2))) return true;
        } while(i<m && (c=='.' || s.charAt(i)==c));
    }
    return false;
}

 

C语言的代码更加简洁:

bool isMatch(char* s, char* p) {
    if(!*p) return !*s;
    if(p[1] != '*') {
        if(!*s || *s != *p && *p != '.') return false;
        return isMatch(s+1, p+1);
    } else {
        int i = -1;
        do {
            if(isMatch(++i+s, p+2)) return true;
        } while(s[i] && (s[i]==*p || *p=='.'));
    }
    return false;
}

 

或者这样:

bool isMatch(const char *s, const char *p) {
    if(!*p) return !*s;
    if(*(p+1) != '*') {
        if(!*s || *s != *p && *p != '.') return false;
        return isMatch(s+1, p+1);
    } else {
        int i = -1;
        do {
            if(isMatch(++i+s, p+2)) return true;
        } while(*(s+i) && (*(s+i)==*p || *p=='.'));
    }
    return false;
}

 

Reference:

http://leetcode.com/2011/09/regular-expression-matching.html

分享到:
评论

相关推荐

    c语言-leetcode 0010-regular-expression-matching.zip

    c c语言_leetcode 0010_regular_expression_matching.zip

    js-leetcode题解之10-regular-expression-matching.js

    js js_leetcode题解之10-regular-expression-matching.js

    C语言-leetcode题解之10-regular-expression-matching.c

    c语言入门 C语言_leetcode题解之10-regular-expression-matching.c

    LeetCode题解 - Java语言实现-181页.pdf

    8. Regular Expression Matching in Java 正则表达式匹配是一个字符串问题,要求使用正则表达式来匹配字符串。可以使用Java的Pattern和Matcher类来解决该问题。 9. Merge Intervals 区间合并是一个数组问题,要求...

    leetcode338-LeetCode:LeetCode刷题总结

    10.Regular Expression Matching 11.Container With Most Water 12.Integer to Roman 13.Roman to Integer 14.Longest Common Prefix (Trie树待完成) 15.3Sum 16.3Sum Closest 17.Letter Combinations of a Phone ...

    leetcode中国-leetcode:leetcode刷题

    Expression Matching 递归匹配 wildcard matching 动态规划 longest common prefix , 简单 valid number, hard, 用有限自动机 integer to roman ,easy , 模拟 roman to integer ,easy , 模拟 count and say , easy ,...

    leetcode530-algorithm:算法

    Expression Matching 011 Container With Most Water 012 Integer to Roman 013 Roman to Integer 014 Longest Common Prefix 015 3Sum 016 3Sum Closest 017 Letter Combinations of a Phone Number 018 4Sum 020 ...

    leetcode跳跃-LeCode:乐科

    leetcode 跳跃 LeetCode Solved by ...Expression Matching 正则表达式匹配 11. Container With Most Water 盛最多水的容器 12. Integer to Roman 整数转罗马数字 13. Roman to Integer 罗马数字转

    leetcode答案-leetcode:leetcode

    leetcode 答案 leet code 这是我的leetcode答案,语言主要是用python。很多算法不是最优,甚至很槽糕,有空就会优化 目前完成了: Two Sum Add Two Numbers Longest ...Regular Expression Matching

    _leetcode-python.pdf

    - Regular Expression Matching: 给定一个输入字符串和一个模式,实现支持'.'和'*'的正则表达式匹配。 - Container With Most Water: 给定一个数组,其中每个元素代表一个宽度为1的柱子高度,要求找出两个柱子,使得...

    分割数组求最大差值leetcode-Leetcode-Road:LeetCode刷题记录

    分割数组求最大差值leetcode LeetCode 学习之路 记录自己完成LeetCode的代码和结果。 序号 中文名称 英文名称 通过率 难度 1 Two Sum 47.0% 简单 2 Add Two Numbers 36.0% 中等 3 Longest Substring Without ...

    leetcode分类-leetcode:leetcode刷题

    4. **正则表达式匹配**:“实现一个简单的正则表达式匹配器”(Regular Expression Matching),涉及到递归和动态规划。 5. **字符串编码与解码**:“无重复字符的最长子串”(Longest Substring Without Repeating...

    lrucacheleetcode-leetcode-1:leetcode-1

    lru cache leetcode Leetcode ...Expression Matching 动态规划,列出转换方程即可,注意初值 记T[i][j] = 是否S[0:i]和P[0:j]匹配 再分类讨论,其中pattern *分为0, 1, more三种类型 0: i不变, j+1

    LeetCode-in-Golang:使用 Golang 解答 LeetCode

    35%2☆ ☆27%3☆ ☆24%4☆ ☆ ☆21%5☆ ☆25%6☆ ☆26%7☆24%8☆ ☆13%9Palindrome Number☆35%10Regular Expression Matching☆ ☆ ☆24%:red_heart:11Container With Most Water☆ ☆36%12Integer to R

    leetcode写题闪退-LeetCode:leetcodeOJ

    leetcode写题闪退 #*的多少代表此题的有意思程度 有几题第一次写的时候思绪比较混乱: *****Regular Expression Matching 2014.10.29 对于Find Minimum in Rotated Sorted Array II 和 Find Minimum in Rotated ...

    lrucacheleetcode-luoleet:LeetcodesolutionsbyXinhangLuoandQinghaoDai

    https://leetcode.com/problems/regular-expression-matching/ Regular Expression Matching 100 https://leetcode.com/problems/same-tree/ Same Tree 101 https://leetcode.com/problems/symmetric-tree/ ...

    lrucacheleetcode-leetcode:leetcodesolutionsinC++微信公众号:曲奇泡芙(互联网&智能汽车技术)

    lru cache leetcode leetcode leetcode solutions in C++ 微信公众号:曲奇泡芙 (互联网&车联网技术) ..../0010-regular-expression-matching.cpp ./0011-container-with-most-water.cpp ./0012-int

    lrucacheleetcode-LeetCode_Note:leetcode个人笔记

    [10_regular-expression-matching.cpp] [100_same-tree.cpp] [1001_sorted-merge-lcci.cpp] [101_对称树.cpp] [102_binary-tree-level-order-traversal.cpp] [103_binary-tree-zigzag-level-order-traversal.cpp] ...

    leetcode怎么销号-leetcodeAns:leetcode问题的答案python

    10.Regular Expression Matching: 递归的方法:当前正则第二个字符不为'*',很简单,比较当前,两个指针都往右移动即可,继续这样比较。如果为空,则有两种方式,第一种是正则的指针往后移动,字符串的保持不变,另一...

    Python_leetcode.zip

    "regular-expression-matching.py"考察的是字符串匹配和回溯算法。Python的字符串操作和递归可以构建出复杂的正则表达式匹配算法,帮助解决复杂的文本处理问题。 "palindrome-pairs.py"是关于回文串和字符串匹配的...

Global site tag (gtag.js) - Google Analytics