Regular Expression Matching
2013-10-23 08:08
295 查看
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 这一题麻烦的地方在于回溯, 如果查到某个是*,则要往前退。
public class Solution { public boolean isMatch(String s, String p) { // Start typing your Java solution below // DO NOT write main() function assert(p!=null && (p.length()==0 || p.charAt(0)!='*')); if(p.length()==0) return s.length()==0; if(p.length()==1 || p.charAt(1)!='*'){ if(s.length()<1 || (p.charAt(0)!='.' && p.charAt(0)!=s.charAt(0))) return false; return isMatch(s.substring(1),p.substring(1)); } else{ int i=-1; while(i<s.length() && (i<0 || p.charAt(0)=='.' || p.charAt(0)==s.charAt(i))){ if(isMatch(s.substring(i+1),p.substring(2))) return true; i++; } return false; } } }
相关文章推荐
- SAX解析XML文件
- 几种常见的排序方法
- PageRank程序的输入部分
- 是男人就做的50道题目 题解
- 简单的DOM解析XML文件,并实现增,删,改,查的操作
- 同事和朋友
- Java vs C++ (6) 构造器中调用虚函数
- sqlite3使用简单介绍
- java中四种操作(DOM、SAX、JDOM、DOM4J)xml方式详解
- c++ 如果函数无参数,那么应声明其参数为 void
- mongodb的地理位置索引
- 使用SQLServer 2008的CDC功能实现数据变更捕获
- SpringAOP之学习总结
- xcode5-ios7-如何添加120x120图标(ios7图标命名)
- 使用ViewPager需要注意的地方
- Perl file checking --- How to get information about a file
- Struts2中使用FreeMarker充当表现层
- 使用mybatis操作mysql数据库SUM方法返回NULL解决
- 如何在线升级Linux mint 14至最新版本的Linux mint 15
- C++语言的表达式模板:表达式模板的入门性介绍