[Leetcode] Regular Expression Matching (Java)
2013-12-27 09:40
351 查看
Implement regular expression matching with support for
正则匹配,p为正则表达式,s为要匹配字符串,‘.’代表任意字符,‘a*’代表能出现0次或多次a,要返回是否能整体匹配而不是部分匹配。
1)p 0位要考虑的情况有点儿多
2)p 1位
3)p的第二位不为‘*’,则s位数要大于1,s第一位==p第一位或p第一位为‘.’,之后继续比较后面
4)p第二位为‘*’,则考虑几种情况:
a)s= abbbbbc ,p= ab*c
b)s=abcabcab ,p= a.*c.*b等
都要迭代比较
'.'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
正则匹配,p为正则表达式,s为要匹配字符串,‘.’代表任意字符,‘a*’代表能出现0次或多次a,要返回是否能整体匹配而不是部分匹配。
1)p 0位要考虑的情况有点儿多
2)p 1位
3)p的第二位不为‘*’,则s位数要大于1,s第一位==p第一位或p第一位为‘.’,之后继续比较后面
4)p第二位为‘*’,则考虑几种情况:
a)s= abbbbbc ,p= ab*c
b)s=abcabcab ,p= a.*c.*b等
都要迭代比较
public class RegularExpressionMatching { public boolean isMatch(String s, String p) { if(p.length()==0) return s.length()==0; if(p.length()==1) return s.length()==1&&(p.charAt(0)==s.charAt(0)||(p.charAt(0)=='.'&&s.length()!=0)); else if(p.charAt(1)!='*') return (s.length()>0)&&(s.charAt(0)==p.charAt(0)||(p.charAt(0)=='.'&&s.length()!=0))&&isMatch(s.substring(1), p.substring(1)); int sIndex = 0; int pIndex = 0; while (sIndex<s.length()&&pIndex<p.length()&&(s.charAt(sIndex)==p.charAt(pIndex)||(p.charAt(pIndex)=='.'&&s.length()!=0))) { if(isMatch(s.substring(sIndex), p.substring(pIndex+2))) return true; sIndex++; } return isMatch(s.substring(sIndex), p.substring(pIndex+2)); } public static void main(String[] args) { String s = "ab"; String p = ".bab"; System.out.println(new RegularExpressionMatching().isMatch(s, p)); } }
相关文章推荐
- LeetCode 10 Regular Expression Matching (C,C++,Java,Python)
- Regular Expression Matching leetcode java
- Regular Expression Matching Leetcode Java
- [LeetCode][10]Regular Expression Matching解析 -Java实现
- LeetCode : Regular Expression Matching [java]
- LeetCode – Regular Expression Matching in Java
- 【JAVA、C++】LeetCode 010 Regular Expression Matching
- Leetcode题解---Regular Expression Matching Java实现
- Java [leetcode 10] Regular Expression Matching
- leetcode Regular Expression Matching(Java)
- LeetCode – Regular Expression Matching in Java
- [LeetCode][Java] Regular Expression Matching
- [LeetCode]Regular Expression Matching、Wildcard Matching
- leetcode - Regular Expression Matching
- 刷LeetCode(10)——Regular Expression Matching
- LeetCode-Regular Expression Matching
- leetcode: Regular Expression Matching
- LeetCode 10 - Regular Expression Matching
- LeetCode—10.Regular Expression Matching
- Leetcode_regular-expression-matching