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

leetcode 10. Regular Expression Matching

时间:2017-07-11 15:53:42      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:string   情况   exp   span   als   har   aaa   should   examples   

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.p为空,那s必然也为空

2.s为空,看p的第二字符是否为*,为*的话 则为isMatch(s,p.substring(2));

3.都不为空,p的第二字符为*,一种情况是直接跳过*部分isMatch(s,p.substring(2)),一种情况是首字符相等isMatch(s.substring(1),p),一种情况是p首字符是.

4.都不为空,p的第二字符不为*,看首字符是否相等

 

 1 public class Solution {
 2     public boolean isMatch(String s, String p) {
 3          if ("".equals(p))
 4             return "".equals(s);
 5         else if ("".equals(s)){
 6             if (p.length()>1&&p.charAt(1)==‘*‘){
 7                 return isMatch(s,p.substring(2));
 8             }else
 9                 return false;
10         }
11         else if (p.length()>1&&p.charAt(1)==‘*‘){
12             if (isMatch(s,p.substring(2)))//skip .*
13                 return true;
14             else if(s.charAt(0)==p.charAt(0)||p.charAt(0)==‘.‘){
15                 return isMatch(s.substring(1),p);
16             }else {
17                 return  false;
18             }
19         }else {
20             if (p.charAt(0)==s.charAt(0)||p.charAt(0)==‘.‘)
21                 return isMatch(s.substring(1),p.substring(1));
22             else
23                 return false;
24         }
25     }
26 }

 

leetcode 10. Regular Expression Matching

标签:string   情况   exp   span   als   har   aaa   should   examples   

原文地址:http://www.cnblogs.com/sure0328/p/7150605.html

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