leetcode 10. Regular Expression Matching
阿新 • • 發佈:2017-07-11
fun example expr blog col 不為 some 跳過 bsp
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). 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
1.p為空,那s必然也為空
2.s為空,看p的第二字符是否為*,為*的話 則為isMatch(s,p.substring(2));
3.都不為空,p的第二字符為*,一種情況是直接跳過*部分isMatch(s,p.substring(2)),一種情況是首字符相等isMatch(s.substring(1),p),一種情況是p首字符是.
4.都不為空,p的第二字符不為*,看首字符是否相等
1 public class Solution { 2 public boolean isMatch(String s, String p) { 3 if ("".equals(p))4 return "".equals(s); 5 else if ("".equals(s)){ 6 if (p.length()>1&&p.charAt(1)==‘*‘){ 7 return isMatch(s,p.substring(2)); 8 }else 9 return false; 10 } 11 else if (p.length()>1&&p.charAt(1)==‘*‘){12 if (isMatch(s,p.substring(2)))//skip .* 13 return true; 14 else if(s.charAt(0)==p.charAt(0)||p.charAt(0)==‘.‘){ 15 return isMatch(s.substring(1),p); 16 }else { 17 return false; 18 } 19 }else { 20 if (p.charAt(0)==s.charAt(0)||p.charAt(0)==‘.‘) 21 return isMatch(s.substring(1),p.substring(1)); 22 else 23 return false; 24 } 25 } 26 }
leetcode 10. Regular Expression Matching