LeetCode-10. Regular Expression Matching
2016-05-05 21:11
260 查看
Implement regular expression matching with support for
这道题好难,,,尝试了几种方法,都不能包括所有的情况,然后去网上看了下别人的代码,好厉害~是用迭代的想法,主要思路如下(摘抄):
1、考虑特殊情况即*s字符串或者*p字符串结束。
(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配
(2)*s字符串未结束,而*p字符串结束,则无法匹配
2、*s字符串与*p字符串均未结束
(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。
(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较,
只要匹配一种情况就算完全匹配
代码如下~
'.'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、考虑特殊情况即*s字符串或者*p字符串结束。
(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配
(2)*s字符串未结束,而*p字符串结束,则无法匹配
2、*s字符串与*p字符串均未结束
(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。
(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较,
只要匹配一种情况就算完全匹配
代码如下~
public boolean isMatch(String s, String p) { if(s.length() == 0){ if(p.length() == 0 || (p.length()>1 && p.charAt(1) == '*' && isMatch(s,p.substring(2,p.length())))){ return true; }else{ return false; } }else if(p.length() == 0){ return false; } if(p.length() == 1 || p.charAt(1) != '*'){ if(p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)){ return isMatch(s.substring(1,s.length()),p.substring(1,p.length())); } else{ return false; } }else{ if(p.charAt(0) !='.' && p.charAt(0) != s.charAt(0)){ return isMatch(s,p.substring(2,p.length())); } else{ if(isMatch(s.substring(0,s.length()),p.substring(2,p.length()))) return true; int i = 0; while(p.charAt(0) == '.' || p.charAt(0) == s.charAt(0+i)){ System.out.println(i); if(isMatch(s.substring(i+1,s.length()),p.substring(2,p.length()))) return true; if(i+1 == s.length()) break; i++; } return false; } } }
相关文章推荐
- NYOJ-183赚钱啦,bellman//spfa水过,,题还是蛮变态的赶脚~~
- 关于View.getHeight和getWidth为0的解决方案(待深入学习)
- 原型模式(Prototype)以及深浅复制
- 快速排序复习
- Hadoop2.4.1伪分布式搭建
- leetcode_097 Interleaving String
- 详解mysql int数字类型的长度值大小上限
- Spring的反射工具类 ReflectionUtils
- 地图处理之基本使用汇总
- 要读的论文
- 关于堆栈的一些认识
- Android Volley增加Https支持,允许SSL
- linux添加用户、权限
- 克隆或复制VMware虚拟机时的网络设置
- JAVA——集合类
- NYOJ 题目860 又见01背包
- 高斯图像滤波原理及其编程离散化实现方法
- memcache简介以及使用方法
- 斜率dp
- 20.从上往下打印二叉树