题目
10. 正则表达式匹配
题解
回溯思想
1 因为这题目中提到:
所谓匹配,是要涵盖 整个 字符串
s
的,而不是部分字符串。
所以这题就简单了。
1 判断是否当前的字符是否相等或者 p
的当前字符是 .
- 若为
true
:继续判断p
的后一个字符是否为*
:- 是
*
:保持当前的p游标,而且接着判断s的下一个字符。 - 不是
*
:保持当前的p游标,而且接着判断s的下两个字符(其实忽略当前的不匹配的字符和*
字符)。
- 是
- 若为
false
:继续判断p
的后一个字符是否为*
:- 是
*
:保持当前的p游标,而且接着判断s的下两个字符(其实忽略当前的不匹配的字符和*
字符)比如说:s="", p=“a*”; 这种情况下,依然可以判断为true。 - 不是
*
:可以退出了。
- 是
2 如果两个字符串都到了末尾了,那么就返回 true
3 如果已经判断为true
了,那么就退出即可。
private int pLen = 0;
private int sLen = 0;
private boolean ans = false;
public boolean isMatch(String s, String p) {
if (s.length() == 0 && p.length() == 0) {
return true;
}
char[] sChars = s.toCharArray();
char[] pChars = p.toCharArray();
sLen = sChars.length;
pLen = pChars.length;
dfs(0, 0, sChars, pChars);
return ans;
}
private void dfs(int sIndex, int pIndex, char[] sChars, char[] pChars ) {
if (ans) {
return;
}
if (pIndex >= pLen) {
if (sIndex >= sLen) {
ans = true;
}
return;
}
boolean isMatched = sIndex < sLen && (pChars[pIndex] == '.' || sChars[sIndex] == pChars[pIndex]);
if (pIndex + 1 < pLen && pChars[pIndex + 1] == '*') {
dfs(sIndex, pIndex + 2, sChars, pChars);
if (isMatched) {
dfs(sIndex + 1, pIndex, sChars, pChars);
}
} else if (isMatched){
dfs(sIndex+1, pIndex+1, sChars, pChars);
}
}