leetcode 10. Regular Expression Matching
来源:互联网 发布:税友软件集团 编辑:程序博客网 时间:2024/06/07 13:33
题目(难)
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
代码
public class Solution { public static boolean isMatch(String s, String p) { return isM(s, p, 0, 0); } public static boolean isM(String s, String p, int i, int j){ if(j >= p.length()){ // pattern已经用光 return i >= s.length(); // 如果s已经走完则匹配,否则不匹配 } if(j == p.length()-1){ // 如果pattern的j已经走到最后一个字符,如果想匹配,则s的i也必须在最后一个,且相等 return (i == s.length()-1) && (s.charAt(i)==p.charAt(j) || p.charAt(j)=='.'); } // 如果pattern的下一个字符(j+1)不是* if(j+1<p.length() && p.charAt(j+1) != '*'){ if(i == s.length()){ // 如果s已经走完,则说明不匹配 return false; } if(s.charAt(i)==p.charAt(j) || p.charAt(j)=='.'){ // 如果当前字符匹配 return isM(s, p, i+1, j+1); // 继续下一个字符判断 }else{ // 如果当前字符不匹配,直接返回false return false; } } // 如果下一个字符(j+1)是* 且 当前字符匹配,则进行搜索: while(i<s.length() && j<p.length() && (s.charAt(i)==p.charAt(j) || p.charAt(j)=='.')){ // 因为*可以取0,1,2,...所以i=i,i+1,i+2,...对所有可能进行测试 // 最后能否匹配取决于剩下的匹配是否成功 if(isM(s, p, i, j+2)){ // 只要找到一个匹配成功即可 return true; } i++; } // 如果下一个字符(j+1)是* 且 当前字符不匹配,则pattern跳过两个,继续比较 // 还有一种情况到这里是上面的最后一次尝试(i==s.length()) return isM(s, p, i, j+2); } }
0 0
- [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
- 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
- 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
- leetcode 10. Regular Expression Matching
- Leetcode-10. Regular Expression Matching
- 【leetcode】10. Regular Expression Matching
- 操作系统思考 第十章 条件变量
- hive中Buckets详解
- yum升级PHP5.0.1->PHP5.3.0
- 一种单片机的滤波算法(转)
- cs231n - assignment1 - softmax 梯度推导
- leetcode 10. Regular Expression Matching
- 使用Docker+Jenkins 搭建CI 自动部署
- PHP在Linux 操作系统下开发环境的搭建题
- Github for windows 使用教程(二)
- 关于listview最后一项i遮盖问题
- 【程序】给C++的cout和fstream添加Unicode支持,使其能向屏幕或文件输入/输出wchar_t字符串
- java线程
- Asp.net总结
- 水库采样