leetcode-10 Regular Expression Matching

来源:互联网 发布:最好的php 分销系统 编辑:程序博客网 时间:2024/06/03 15:18

问题描述

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