算法代码

正则表达式匹配

2020-05-31  本文已影响0人  windUtterance

题目描述:给你一个字符串s和一个字符规律p,请你来实现一个支持 '.'和'*'的正则表达式匹配。

'.' 匹配任意单个字符

;'*' 匹配零个或多个前面的那一个元素

示例:输入:

输入:
s = "aab"
p = "cab"
输出: true
解释: 因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。

java代码

class Solution {
    public boolean isMatch(String text, String pattern) {
        if(pattern.isEmpty()) return text.isEmpty();
        boolean first_match = (!text.isEmpty() && 
                                (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
        
        if(pattern.length() >= 2 && pattern.charAt(1) == '*') {
            return (isMatch(text, pattern.substring(2)) || 
                    (first_match && isMatch(text.substring(1), pattern)));
        } else {
            return (first_match && isMatch(text.substring(1), pattern.substring(1)));
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读