【LeetCode】10. Regular Expression Matching - Java實現
文章目錄
1. 題目描述:
Given an input string (s
) and a pattern (p
), 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
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 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 = “c*a*b”
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 = “mis*is*p*.”
Output: false
2. 思路分析:
題目的意思是實現一種正則表示式的匹配。首先對於題意:
- “a"對應"a”, 這種匹配不解釋了;
- 任意字母對應".", 這也是正則常見;
- 0到多個相同字元x,對應"x*", 比起普通正則,這個地方多出來一個字首x,x代表的是相同的字元中取一個,比如"aaaab"對應是"a*b";
- "*“還有一個易於疏忽的地方就是它的"貪婪性"要有一個限度,比如"aaa"對應"a*a”,程式碼邏輯不能一路貪婪到底;
正則表示式如果期望著一個字元一個字元的匹配,是非常不現實的,而"匹配"這個問題,非常容易轉換成"匹配了一部分",整個匹配不匹配,要看"剩下的匹配"情況,這就很好的把一個大的問題轉換成了規模較小的問題:遞迴。
3. Java程式碼:
原始碼
:見我GiHub主頁
程式碼:
public static boolean isMatch(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
// 表示第一個字元是否匹配上
boolean first_match = (s.length() != 0 && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'));
// 如果pattern是"x*"型別的話,那麼pattern每次要兩個兩個的減少。否則,就是一個一個的減少
if (p.length() == 1 || p.charAt(1) != '*') {
return first_match && isMatch(s.substring(1), p.substring(1));
} else {
return (isMatch(s, p.substring(2)) ||
(first_match && isMatch(s.substring(1), p)));
}
}