leetcode-10 Regular Expression Matching
来源:互联网 发布:最好的php 分销系统 编辑:程序博客网 时间:2024/06/03 15:18
问题描述:
Implementregular 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 { /** 显然'.'是比较容易处理的,s,p同时跳过就可以 * 而'*'代表多个字符,故需要分情况进行特殊讨论 **/ public boolean isMatch(String s,String p) { // 显然p为空时,s为空才会返回true if (p.isEmpty()) return s.isEmpty(); int i = 0; // c为字符串p在i位置的值 for (char c = p.charAt(0); i < p.length(); s = s.substring(1), c = i < p.length() ? p.charAt(i) : ' ') { // 分两种情况判断,第一种是第i+1位元素不是'*'情况 if (i + 1 >= p.length()|| p.charAt(i + 1) != '*') i++; // p下一位是'*'情况 (由于这里[i+1]元素一定存在,故p.substring(i+2)至多为"",不会出现越界错误) else if (isMatch(s,p.substring(i + 2))) return true; // 出现不匹配情况直接返回false if (s.isEmpty() || (c != '.' && c !=s.charAt(0))) return false; /** 注意当[i+1]为'*'时,此时i是不变的;若isMatch(s, p.substring(i + 2))为false,表示'*'代表的不止一个字符, * 此时s也未做改变,i在为匹配成功前都不会改变,故依然是s继续下一个字节与'*'前这个字节[i]作比较,一直往后推移,直至 isMatch(s, p.substring(i + 2))为true, * 则表示匹配成功;**/ } // 一直遍历到p位空的情况,则最后也需要判断s是否为空 return s.isEmpty(); }}
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-10Regular Expression Matching
- leetcode-10 Regular Expression Matching
- leetcode 10: Regular Expression Matching
- leetcode 10 Regular Expression Matching
- 关于导航栏和状态栏的一些UI设置
- MySQL命令显示所有可供查询的分类
- asp.net将sql语句封装在类库中
- html初学-基础
- Lapack安装与测试
- leetcode-10 Regular Expression Matching
- SQL Server 2008 数据库同步
- Block的简单记录
- LeetCode(73)Set Matrix Zeroes
- ImageView在开启硬件加速时加载长图
- 解决js 在onkeydown事件按键停顿问题
- Objective-C Runtime 运行时之一:类与对象
- hdu 4427 三维dp
- modal一个导航控制器