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

leetcode Regular Expression Matching

时间:2014-12-25 23:21:17      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

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 Solution {
 2     public boolean isMatch(String s, String p) {
 3         if (s.equals(p)) {
 4             return true;
 5         }
 6         
 7         int lenS=s.length();
 8         int lenP=p.length();
 9         if (lenP==0) {
10             return lenS==0;
11         }
12         if (lenP==1) {
13             if (p.equals(s)||(p.equals(".")&&lenS==1)) {
14                 return true;
15             }else {
16                 return false;
17             }
18         }
19         
20         if (p.charAt(1)!=‘*‘) {
21             if (lenS>0
22                     &&(s.charAt(0)==p.charAt(0)||p.charAt(0)==‘.‘)) {
23                 return isMatch(s.substring(1), p.substring(1));
24             }
25             return false;
26         }else {
27             while (s.length()>0&&
28                     (s.charAt(0)==p.charAt(0)||p.charAt(0)==‘.‘)) {
29                 if (isMatch(s, p.substring(2))) {
30                     return true;
31                 }
32                 s=s.substring(1);
33             }
34             return isMatch(s, p.substring(2));
35         }
36     }
37 }

 

leetcode Regular Expression Matching

标签:

原文地址:http://www.cnblogs.com/birdhack/p/4185685.html

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