【每天一道编程系列-2018.2.27】(Ans)

时间:2022-06-19
本文章向大家介绍【每天一道编程系列-2018.2.27】(Ans),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【题目描述】

  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 

【题目大意】

  实现一个正则表达式匹配算法,.匹配任意一个字符,*匹配0个或者多个前导字符 

【解题思路】

  使用标记匹配算法法,从后向前进行匹配。 

【本题答案】

import java.util.Arrays;

/**
 * @author yesr
 * @create 2018-02-27 下午11:04
 * @desc 正则表达式匹配
 **/
public class Test0227 {
    /**
     * 010-Regular Expresssion Matching(正则表达式匹配)
     *
     * @param s 匹配串
     * @param p 模式串
     * @return 匹配结果,true匹配,false不匹配
     */
    public boolean isMatch(String s, String p) {
        // 标记数数组
        boolean[] match = new boolean[s.length() + 1];
        // 初始化
        Arrays.fill(match, false);
        // 假定最后的结果是匹配的
        match[s.length()] = true;

        // 对模式串从后向前进行处理
        for (int i = p.length() - 1; i >= 0; i--) {

            // 如果当前是*
            if (p.charAt(i) == '*') {

                // 匹配串从最后一个开始处理
                for (int j = s.length() - 1; j >= 0; j--)  {
                    match[j] = match[j] || match[j + 1] && (p.charAt(i - 1) == '.' || s.charAt(j) == p.charAt(i - 1));
                }
                i--;
            }
            // 如果不是*
            else {
                for (int j = 0; j < s.length(); j++) {
                    match[j] = match[j + 1] && (p.charAt(i) == '.' || p.charAt(i) == s.charAt(j));
                }

                match[s.length()] = false;
            }
        }
        return match[0];
    }
}