LeetCode 010 Regular Expression Matching - Java

Implement regular expression matching with support for '.' and '*'.express

'.' 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

 

定位:困難題spa

題目給出兩種匹配規則,即'.'能匹配任何字符,'*'能夠將前面一個字符重複0到任意次。prototype

此時咱們將'*'與其前一個字符合看爲一個單元考慮。存在如下狀況:code

  • 兩個字符串長度均爲0,返回true;
  • 前一個長度爲0,後一個均爲含'*'單元,返回true;
  • 取前一個的前項字符與後一個前項字符,如若前一個前項爲重複字符,取到不重複位置,後一個判斷是否有'*'單元進行匹配,匹配正確去除已匹配部分將其他遞歸,不匹配返回false。

 

Java實現:blog

 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 }
相關文章
相關標籤/搜索