【LeetCode】#10正則表示式匹配(Regular Expression Matching)
【LeetCode】#10正則表示式匹配(Regular Expression Matching)
題目描述
給定一個字串 (s) 和一個字元模式 §。實現支援 ‘.’ 和 ‘’ 的正則表示式匹配。
‘.’ 匹配任意單個字元。
'’ 匹配零個或多個前面的元素。
匹配應該覆蓋整個字串 (s) ,而不是部分字串。
說明:
s 可能為空,且只包含從 a-z 的小寫字母。
p 可能為空,且只包含從 a-z 的小寫字母,以及字元 . 和 *。
示例
示例 1:
輸入:
s = “aa”
p = “a”
輸出: false
解釋: “a” 無法匹配 “aa” 整個字串。
示例 2:
輸入:
s = “aa”
p = “a*”
輸出: true
解釋: ‘*’ 代表可匹配零個或多個前面的元素, 即可以匹配 ‘a’ 。因此, 重複 ‘a’ 一次, 字串可變為 “aa”。
示例 3:
輸入:
s = “ab”
p = “."
輸出: true
解釋: ".” 表示可匹配零個或多個(’*’)任意字元(’.’)。
示例 4:
輸入:
s = “aab”
p = “cab”
輸出: true
解釋: ‘c’ 可以不被重複, ‘a’ 可以被重複一次。因此可以匹配字串 “aab”。
示例 5:
輸入:
s = “mississippi”
p = “misis
輸出: false
Description
Given an input string (s) and a pattern §, 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example
Example 1:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input:
s = “aa”
p = “a*”
Output: true
Explanation: ‘*’ means zero or more of the precedeng element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”.
Example 3:
Input:
s = “ab”
p = “."
Output: true
Explanation: ".” means “zero or more (*) of any character (.)”.
Example 4:
Input:
s = “aab”
p = “cab”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches “aab”.
Example 5:
Input:
s = “mississippi”
p = “misisp*.”
Output: false
解法
class Solution{
public boolean isMatch(String s, String p){
if(p.isEmpty())
return s.isEmpty();
boolean first = (!s.isEmpty() && (p.charAt(0)==s.charAt(0) || p.charAt(0)=='.'));
if(p.length()>=2 && p.charAt(1)=="*"){
return (isMatch(s, p.substring(2)) || (first && isMatch(text.substring(1), p)));
}else{
return first && isMatch(s.substring(1), p.substring(1));
}
}
}