LeetCode_Regular Expression Matching
2015-05-01 19:36
302 查看
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
模拟正则表达式的匹配,要求是:输入两个字符串s和p,前一个s中为标准字符,后一个p中含有“.”和“*”这两种特殊的字符,有特殊的含义,其中“.”代表匹配任意单个字符,“*”代表*之前的那个字符可以重复0~n次(这个需要注意,不是说“*”本身代表任意一个字符重复0~n次),原题中还给出了很多个例子,这道题使用递归,或者说是回溯法。
所以,解题的关键在于判断当前字符的下一个字符是否为“*”。1、若为“*”,则循环遍历s字符串(s字符串每次截取第一个字符,即s=s.substring(1))是否与p.substring(2)相等,一旦相等则返回true,若遇到不等的情况,则继续判断当前的s与p.substring(2)是否相等(递归处理);2、若不为“*”,情况就简单了,直接判断两字符串的第一个字符是否相等或p的第一字符是否为“.”,然后两字符串截取第一个字符后,剩下的字符组成的新字符串再递归调用该方法判断。
java解题:
public static boolean isMatch(String s, String p) { if(p.length()==0) return (s.length()==0); if(p.length()==1){ if(p.equals(".")) return s.length()==1; else return p.equals(s); } if(p.charAt(1)!='*'){ if(s.length()>0) if(p.charAt(0)=='.') return isMatch(s.substring(1),p.substring(1)); else{ return((s.charAt(0)==p.charAt(0)) && isMatch(s.substring(1),p.substring(1))); } else return false; } else{ while(s.length()>0 && (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)); } }
参考:http://my.oschina.net/jdflyfly/blog/283584
相关文章推荐
- leetcode Regular Expression Matching
- Regular Expression Matching -- LeetCode
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
- [LeetCode] 079: Regular Expression Matching
- [LeetCode]题解(python):010-Regular Expression Matching
- leetcode 10 -- Regular Expression Matching
- LeetCode 10 Regular Expression Matching
- [LeetCode] Regular Expression Matching
- [leetcode] Regular Expression Matching
- LeetCode正则表达式-Regular Expression Matching
- LeetCode之Regular Expression Matching
- LeetCode-Regular Expression Matching
- LeetCode之10_Regular Expression Matching
- LeetCode Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- LeetCode题目解析(二):10、Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- leetcode 10 Regular Expression Matching
- LeetCode | Regular Expression Matching
- Regular Expression Matching_LeetCode