题目:Regular Expression Matchingexpress
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", "cab") → trueprototype
分析:题目要求挺简单的,字符匹配,对.
和*
作特殊处理,字符串的匹配能够拆分红子串的匹配,子串的匹配又可概括为每一个字符的匹配,所以这道题用递归比较方便。code
首先,抛开.
和*
无论,如何递归地判断两个字符串相等呢?递归
public class Solution { public boolean isMatch(String s, String p) { int slen = s.length(); int plen = p.length(); if (slen == 0 && plen == 0) return true; char c0 = getChar(s, 0); char p0 = getChar(p, 0); if (match(c0, p0)) { return isMatch(s.substring(1), p.substring(1)); } return false; } //判断两个字符是否相等 private boolean match(char a, char b) { return a == b; } //为何要这个函数呢,主要是为了统一处理下标越界的问题 //若是越界了,直接返回0便可 private char getChar(String s, int p) { if (s.length() > p) { return s.charAt(p); } return 0; } }
根据题意,.
可根任何字符匹配,那么match
方法就要改为:element
//判断两个字符是否相等 private boolean match(char a, char b) { return a == b || b == '.'; }
因为*
对前一个字符有反作用,故须要对*
进行特殊判断。尤为是[任意字符]*
能够匹配任意长度的字符串,包括空串。所以,每次处理isMatch
时,都要向后探一下接下来是否有*
:字符串
最终代码:get
public class Solution { public boolean isMatch(String s, String p) { int slen = s.length(); int plen = p.length(); if (slen == 0 && plen == 0) return true; char c0 = getChar(s, 0); char p0 = getChar(p, 0), p1 = getChar(p, 1); if (match(c0, p0) || p1 == '*') { if (p1 != '*') { if (slen == 0) return false; return isMatch(s.substring(1), p.substring(1)); } // if p1 is *, * means 0 ~ n int i = 0; boolean ret = isMatch(s.substring(0), p.substring(2)); // try 0 if (ret) return ret; while (i < slen && match(getChar(s, i), p0)) { ret = isMatch(s.substring(i+1), p.substring(2)); // try for every available position if (ret) return ret; i++; } } return false; } private boolean match(char a, char b) { return a == b || b == '.'; } private char getChar(String s, int p) { if (s.length() > p) { return s.charAt(p); } return 0; } }