10. Regular Expression Matching

最近被cloudsim折磨惨了,掉进坑里了~好长时间没有刷题了,今天不搞TMD的cloudsim了,刷题吧

解题一:

这题太没意思了,直接用java自带的正则表达式也能通过

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
    public boolean isMatch(String s, String p) {
        Pattern pattern = Pattern.compile(p);
        Matcher matcher = pattern.matcher(s);
        return matcher.matches();
    }
}

当然我们不能这样想,要看看有没有其他的方法可以学习

解题二:递归

https://www.jianshu.com/p/85f3e5a9fcda

https://www.cnblogs.com/springfor/p/3893593.html

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
    while (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) {  
        if (isMatch(s, p.substring(2))) { 
            return true;                     
        }                                    
        s = s.substring(1);
    }

    return isMatch(s, p.substring(2));
}

解题三:动态规划

https://www.nowcoder.com/questionTerminal/d2ccc8cad7234aa5aa68c42471913b86

链接:https://www.nowcoder.com/questionTerminal/d2ccc8cad7234aa5aa68c42471913b86
来源:牛客网

public class Demo1 {
    /*
     * 如果对动态规划不太了解,可以参考博客:<a href="http://blog.csdn.net/zjkc050818/article/details/74532023" target="_blank">http://blog.csdn.net/zjkc050818/article/details/74532023  * 以及博客中的视频。
     */
    public boolean isMatch(String s, String p) {
        if (s == null || p == null)
            return false;
        int m = s.length(), n = p.length();
        boolean[][] res = new boolean[m + 1][n + 1];
        res[0][0] = true;
        for (int i = 0; i < n; i++) {
            if (p.charAt(i) == '*' && res[0][i - 1])
                res[0][i + 1] = true;
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (p.charAt(j) == '.')
                    res[i + 1][j + 1] = res[i][j];
                if (p.charAt(j) == s.charAt(i))
                    res[i + 1][j + 1] = res[i][j];
                if (p.charAt(j) == '*') {
                    if (s.charAt(i) != p.charAt(j - 1) && p.charAt(j - 1) != '.')
                        res[i + 1][j + 1] = res[i + 1][j - 1];
                    else {
                        //res[i + 1][j - 1] 表示*一个都不匹配;
                        //res[i + 1][j]表示匹配一个 
                        //res[i][j + 1]表示匹配多个
                        res[i + 1][j + 1] = res[i + 1][j - 1] || res[i + 1][j] || res[i][j + 1];
                    }
                }
            }
        }
        return res[m][n];
    }
}

 

posted on 2018-01-09 16:47  Michael2397  阅读(410)  评论(0编辑  收藏  举报

导航