leetcode-10 Regular Expression Matching

问题描述

Implementregular 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


代码

public class Solution {
    /** 显然'.'是比较容易处理的,s,p同时跳过就可以
     *  而'*'代表多个字符,故需要分情况进行特殊讨论 **/
   
    public boolean isMatch(String s,String p) {
        // 显然p为空时,s为空才会返回true
        if (p.isEmpty())
            return s.isEmpty();
 
        int i = 0;
        // c为字符串p在i位置的值
        for (char c = p.charAt(0); i < p.length(); s = s.substring(1), c = i < p.length() ? p.charAt(i) : ' ') {
            // 分两种情况判断,第一种是第i+1位元素不是'*'情况
            if (i + 1 >= p.length()|| p.charAt(i + 1) != '*')
                i++;
            // p下一位是'*'情况 (由于这里[i+1]元素一定存在,故p.substring(i+2)至多为"",不会出现越界错误)
            else if (isMatch(s,p.substring(i + 2)))
                return true;
 
            // 出现不匹配情况直接返回false
            if (s.isEmpty() || (c != '.' && c !=s.charAt(0)))
                return false;
           
            /** 注意当[i+1]为'*'时,此时i是不变的;若isMatch(s, p.substring(i + 2))为false,表示'*'代表的不止一个字符,
             *  此时s也未做改变,i在为匹配成功前都不会改变,故依然是s继续下一个字节与'*'前这个字节[i]作比较,一直往后推移,直至 isMatch(s, p.substring(i + 2))为true,
             *  则表示匹配成功;**/
        }
 
        // 一直遍历到p位空的情况,则最后也需要判断s是否为空
        return s.isEmpty();
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值