码迷,mamicode.com
首页 > 编程语言 > 详细

Java [leetcode 10] Regular Expression Matching

时间:2015-04-25 22:41:59      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

Implement regular expression matching with support for ‘.‘ and ‘*‘.

‘.‘ Matches any single character.
‘*‘ Matches zero or more of the preceding element.
http://i.cnblogs.com/EditPosts.aspx?opt=1
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

解题思路:

从字符串s和p的位置sp,pp处分别开始匹配,运用递归的方法不断缩小字符串的比较长度,最后回溯回来比较结果。

假设现在走到分别走到sp,pp处。则分为下面几种情况:

(1)如果pp的位置已经越界,那么若sp也已越界,那么则返回true;否则说明s字符串还有长度,不匹配,返回false;

(2)pp的位置为p的最后一位,那么此时只能一一匹配,若不匹配则返回false;否则进行下一位比较;

(3)pp的位置比较靠前,那么比较pp的下一位。如果下一位不是‘*‘,则只能一一匹配,若不匹配则返回false;否则进行下一位比较。如果下一位是‘*‘,则将pp的位置向后移动两位,sp的位置从现在开始进行暴力比较,每次向后移一位进行递归比较。

代码如下:

 1 public class Solution {
 2     public static boolean isMatch(String s, String p) {
 3         if (s == null)
 4             return p == null;
 5         if (p == null)
 6             return s == null;
 7         return helper(s, p, 0, 0);
 8     }
 9     private static boolean helper(String s, String p, int sp, int pp) {
10         if (pp >= p.length())
11             return sp >= s.length();
12         // pp comes to end
13         if (pp == p.length() - 1) {
14             if (sp >= s.length()
15                     || (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != ‘.‘))
16                 return false;
17             else
18                 return helper(s, p, sp + 1, pp + 1);
19         }
20         // p.charAt(pp+1)!=‘*‘
21         if (p.charAt(pp + 1) != ‘*‘) {
22             if (sp >= s.length()
23                     || (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != ‘.‘))
24                 return false;
25             else
26                 return helper(s, p, sp + 1, pp + 1);
27         }
28         // p.charAt(pp+1)==‘*‘
29         while (sp < s.length()
30                 && (p.charAt(pp) == ‘.‘ || s.charAt(sp) == p.charAt(pp))) {
31             if (helper(s, p, sp, pp + 2))
32                 return true;
33             sp++;
34         }
35         return helper(s, p, sp, pp + 2);
36     }
37 }

 

Java [leetcode 10] Regular Expression Matching

标签:

原文地址:http://www.cnblogs.com/zihaowang/p/4456805.html

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