leetcode 10. Regular Expression Matching
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 10. Regular Expression Matching相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 10. Regular Expression Matching
leetcode 10. Regular Expression Matching
Leetcode 10: Regular Expression Matching
[LeetCode #10] Regular Expression Matching