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

LeetCode 010 Regular Expression Matching - Java

时间:2017-06-17 17:03:37      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:string   匹配   位置   boolean   难题   length   mil   solution   bst   

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

 

定位:困难题

题目给出两种匹配规则,即‘.‘能匹配任何字符,‘*‘可以将前面一个字符重复0到任意次。

此时我们将‘*‘与其前一个字符合看为一个单元考虑。存在以下情况:

  • 两个字符串长度均为0,返回true;
  • 前一个长度为0,后一个均为含‘*‘单元,返回true;
  • 取前一个的前项字符与后一个前项字符,如若前一个前项为重复字符,取到不重复位置,后一个判断是否有‘*‘单元进行匹配,匹配正确去除已匹配部分将其余递归,不匹配返回false。

 

Java实现:

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

 

LeetCode 010 Regular Expression Matching - Java

标签:string   匹配   位置   boolean   难题   length   mil   solution   bst   

原文地址:http://www.cnblogs.com/zaritiy/p/7040552.html

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