Regular Expression Matching

Posted ncznx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Regular Expression Matching相关的知识,希望对你有一定的参考价值。

描述
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
分析
这是一道很有挑战的题

‘‘匹配任何单个字符。
“*”匹配前一个元素的零个或多个

代码

 1 public class RegularExpressionMatching {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         System.out.println(isMatch("aa","a*"));
 6     }
 7     public static boolean isMatch(String s, String p) {
 8         if (p.length() == 0)
 9             return s.length() == 0;
10 
11         // length == 1 is the case that is easy to forget.
12         // as p is subtracted 2 each time, so if original
13         // p is odd, then finally it will face the length 1
14         if (p.length() == 1)
15             return (s.length() == 1) && (p.charAt(0) == s.charAt(0) || p.charAt(0) == ‘.‘);
16 
17         // next char is not ‘*‘: must match current character
18         if (p.charAt(1) != ‘*‘) {
19             if (s.length() == 0)
20                 return false;
21             else
22                 return (s.charAt(0) == p.charAt(0) || p.charAt(0) == ‘.‘) && isMatch(s.substring(1), p.substring(1));
23         } else {
24             // next char is *
25             while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == ‘.‘)) {
26                 if (isMatch(s, p.substring(2)))
27                     return true;
28                 s = s.substring(1);
29             }
30             return isMatch(s, p.substring(2));
31         }
32     }
33 
34 }

 

















以上是关于Regular Expression Matching的主要内容,如果未能解决你的问题,请参考以下文章

10. Regular Expression Matching

regular expression

Regular Expression Matching

Regular Expression

Regular Expression Matching

10. Regular Expression Matching