【LeetCode-面试算法经典-Java实现】【010-Regular Expresssion Matching(正则表达式匹配)】

126 篇文章 82 订阅

【010-Regular Expresssion Matching(正则表达式匹配)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】

原题

  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;

public class Solution {
    /**
     * 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];
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

这里写图片描述

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/46951847

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值