Regular Expression Matching
来源:互联网 发布:好的手机壁纸软件 编辑:程序博客网 时间:2024/06/07 15:59
题目:
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") return false
isMatch("aa","aa") return true
isMatch("aaa","aa") return false
isMatch("aa", "a*") return true
isMatch("aa", ".*") return true
isMatch("ab", ".*") return true
isMatch("aab", "c*a*b") return true
注意:这里的a*表示a可以重复0次或者多次,不是a和*分开的。
这个问题可以简化为两种情况:第二个字符是'*'和第二个字符不是'*'。
public static boolean isMatch(String s, String p) {if(p.length() == 0) return s.length() == 0; //p's length 1 is special case if(p.length() == 1 || p.charAt(1) != '*'){ // if the length of s is 0 or the first does not match, return false if(s.length() < 1 || (p.charAt(0) != '.' && s.charAt(0) != p.charAt(0))) return false; // otherwise, compare the rest of the string of s and p. return isMatch(s.substring(1), p.substring(1)); }else{ int len = s.length(); //case 2.1: a char & '*' can stand for 0 element,此时 i < 0 //case 2.2: a char & '*' can stand for 1 or more preceding element, so try every sub string int i = -1; while(i<len && (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; } }
0 0
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- leetcode Regular Expression Matching
- [Leetcode] Regular Expression Matching
- Regular Expression Matching
- Regular Expression Matching
- [LeetCode]Regular Expression Matching
- Regular Expression Matching
- LeetCode-Regular Expression Matching
- Regular Expression Matching
- 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
- 数据库事务隔离级别与锁
- [LeetCode][Java] Rotate List
- 13个js图表插件
- gdb基本命令
- poj 2309 BST
- Regular Expression Matching
- 在Ubuntu安装完成后更改默认的语言LANG,出现Cannot set LC_CTYPE to default locale: No such file or directory错误的解决办法
- JAVA基础-IO流
- ARM Linux 3.x 的设备树(Device Tree)之DTB、DTS
- C++学习总结(一)
- 双击运行Java程序
- 世界并不会在乎你的感受, 直到你拥有足够的实力!
- Linux学习笔记,Linux文件系统,文件管理,目录管理
- Mac 显示和隐藏文件夹命令