leetcode No10. Regular Expression Matching
来源:互联网 发布:linux cpu 内存 查看 编辑:程序博客网 时间:2024/05/21 14:56
Question:
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
Algorithm:
设当前字符串s1的下标为i,s2的下标为j
1、s2[i+1]!=' * ',只需往后一一比对
2、s2[i+1]==' * ',分两种情况
(1)s1[i]!=s2[j],相当于后面的*是把s[j]的出现次数置为0,再比对s1[i]和s2[j+2]
(2)s1[i]==s2[j],那么就要维持现有的模式(i++,j位置不变)或置为(1)
Accepted Code:
C:
bool isMatch(char* s, char* p) { if(*s=='\0' && *p=='\0') return true; if(*s!='\0' && *p=='\0') return false; if(*(p+1)!='*') { if((*s!='\0') && (*s==*p || *p=='.')) return isMatch(s+1,p+1); else return false; } else { while((*s!='\0') && (*s==*p || *p=='.')) { if(isMatch(s,p+2)) return true; s++; } return isMatch(s,p+2); } return false;}
C++:这个速度很慢,不知道为啥???用了289ms
class Solution {public: bool isMatch(string s, string p) { return helper(s,p,0,0); } bool helper(string s1,string s2,int i,int j) { if(j==s2.size()) return i==s1.size(); if(s2[j+1]!='*') { if(s1[i]==s2[j] || s2[j]=='.') return helper(s1,s2,i+1,j+1) ; } else { while(i<s1.size() && (s1[i]==s2[j] || s2[j]=='.')) { if(helper(s1,s2,i,j+2)) return true; i++; } return helper(s1,s2,i,j+2); } return false; }};
0 0
- LeetCode : No10 Regular Expression Matching
- leetcode No10. Regular Expression Matching
- No10-Regular Expression Matching
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- leetcode Regular Expression Matching
- [Leetcode] Regular Expression Matching
- [LeetCode]Regular Expression Matching
- LeetCode-Regular Expression Matching
- Regular Expression Matching LeetCode
- LeetCode | Regular Expression Matching
- LeetCode: Regular Expression Matching
- Leetcode: Regular Expression Matching
- [LeetCode] Regular Expression matching
- [LeetCode] Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode Regular Expression Matching
- leetcode: Regular Expression Matching
- Struts Series(6) - 拦截器
- 通讯行业各职位面试题和笔试题
- [转]BMP文件格式详解(BMP file format)
- Java系列(八)__Java面向对象(3)
- 我对c#委托的浅见 使用情景- 两个窗体间的调用操作
- leetcode No10. Regular Expression Matching
- 第十二周:C语言:宏定义
- pf_ring
- java开发规范
- C++头文件循环包含依赖
- Java系列(十)__Java面向对象(4)
- IE无法上网,远程计算机或设备将不接受连接,其他浏览器可用
- 725B
- 修改两个关于RCU锁的bug