码迷,mamicode.com
首页 > 其他好文 > 详细

Regular Expression Matching

时间:2018-06-14 01:04:54      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:The   stat   gen   aaa   nbsp   int   描述   should   cti   

描述
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

标签:The   stat   gen   aaa   nbsp   int   描述   should   cti   

原文地址:https://www.cnblogs.com/ncznx/p/9180591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!