Leetcode - Regular Expression Matching

**
Question:

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

**

Referenced Code:

``````public class Solution {
public boolean isMatch(String s, String p) {
if (p.isEmpty()) {
return s.isEmpty();
}

if (p.length() == 1 || p.charAt(1) != '*') {
if (s.isEmpty() || (p.charAt(0) != '.' && p.charAt(0) != s.charAt(0))) {
return false;
} else {
return isMatch(s.substring(1), p.substring(1));
}
}

//P.length() >=2
while (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'))  {
if (isMatch(s, p.substring(2))) {
return true;
}
s = s.substring(1);
}

return isMatch(s, p.substring(2));
}
}
``````

Test result:

Paste_Image.png

Recursion has helped code become simple.

'含义的理解。"*"表示的是，前面那个字符出现的次数。

``````aa = a*
aaa = a*
ac = ab*c
....
``````

1.前面如果没有字符，即他是字符串的首位，那么，他会想普通字符一样与s中字符进行比较。
2.

1. ".*" 的情况比较特殊。
``````ab = .*
abc = .*
abcd != .*c
abcd = .*abcd
abcd = .*bcd
abcd = .*cd
abcd = .*d
abcd = .*
``````

4.该用何种思路来处理 * 的比较。

``````aaa = a*
aaaaaab = a*b
``````

``````aaaaa = a*a
``````

1.p中第二个字符不是""。 那么，该怎么比就怎么比。
2.p中第二个字符是"
"。那么。就需要用递归。

s = s.substring(1).

``````aaa = a*a
``````

``````s = aaa;
s != a;
s = aa;
s != a;
s = a;
s = a;
return true;
``````

**

**

Anyway, Good luck, Zhidong Liu!

My code:

``````public class Solution {
public boolean isMatch(String s, String p) {
if (p.length() == 0) {
return s.length() == 0;
}
else if (p.length() == 1) {
if (s.length() == 1 && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) {
return true;
}
else {
return false;
}
}
else if (p.charAt(1) != '*') {
if (s.length() == 0) {
return false;
}
else if (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') {
return isMatch(s.substring(1), p.substring(1));
}
else {
return false;
}
}
else {
if (isMatch(s, p.substring(2))) {
return true;
}
while (s.length() > 0 && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) {
s = s.substring(1);
if (isMatch(s, p.substring(2))) {
return true;
}
}
return false;
}
}
}
``````

dfs

s.charAt(0) == p.charAt(0) || p.charAt(0)

'啊。所以我们移动一格并不会破坏顺序。

if (isMatch(s, p.substring(2))) {...}

s = substring(1);

if (isMatch(s, p.substring(2))) {...}

if s.charAt(0) 和 p.charAt(0), 是否匹配。

Anyway, Good luck, Richardo! -- 09/16/2016