leetcode articles

Regular Expression Matching

2018-02-26  本文已影响45人  gattonero

Regular Expression Matching

问题

用包含*和.这两个正则符号的正则表达式来匹配字符串

解决方案

这里就是非贪心的匹配方式,代码量很少,每次只匹配开头的字符,剩余结果由回溯过程得到

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));
        }
    }
}

Tips

上一篇 下一篇

猜你喜欢

热点阅读