LeetCode——Regular Expression Matching
2024-08-30 19:49:49
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
实现支持 ' . '和 ' * '的正則表達式。
' . ' 匹配不论什么单字符。
' * '匹配0或多个前向元素。
使用递归进行推断。
整体上能够分成两种情况,一种是以 ' * ‘开头的,还有一种不是。
public class RegularExpressionMatching {
public static void main(String[] args) {
System.out.println(isMatch("aa","a"));
System.out.println(isMatch("aa","aa"));
System.out.println(isMatch("aaa","aa"));
System.out.println(isMatch("aa", "a*"));
System.out.println(isMatch("aa", ".*"));
System.out.println(isMatch("ab", ".*"));
System.out.println(isMatch("aab", "c*a*b"));
}
public static boolean isMatch(String s,String p){
if(p.length() == 0)
return s.length() == 0;
if(p.length() == 1 || p.charAt(1) != '*'){
if(s.length() < 1 || (p.charAt(0) != '.' && s.charAt(0) != p.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;
} }
}
Reference:http://www.programcreek.com/2012/12/leetcode-regular-expression-matching-in-java/
最新文章
- scp命令[转]
- CDH 2、Cloudera Manager的安装
- Conscription
- hihocoder第41周 骨牌覆盖(矩阵快速幂)
- HTTP协议与HTML form
- Tomcat学习笔记(一)一个简单的Web服务器
- 张高兴的 Xamarin.Android 学习笔记:(一)环境配置
- POI 导出导入工具类介绍
- 浅谈mybatis如何半自动化解耦
- websocket 的客户端 websocket-sharp
- response slider
- PHP完美分页类
- Linux 系统及编程相关知识总汇
- Android使用http协议与服务器通信
- Intro.js的简介和用法
- Bzoj3597: [Scoi2014]方伯伯运椰子
- cacti (不可以利用yum安装cacti的配置)
- 如何在 Ubuntu 上搭建网桥
- Uboot详细解析1
- numEdit
热门文章
- CSU 2018年12月月赛 F(2218): Finding prime numbers
- mybatis中修改了数据,控制台显示成功,数据库没有修改
- 常见的Redis问题?
- 九度oj 题目1192:回文字符串
- Oracle导出txt文本文件
- MYSQL Sorting result 把队列堆满了,该怎么办?
- K-th Number POJ - 2104 划分树
- 2018/3/14 Hadoop学习笔记(一)
- Ubuntu 16.04使用百度云的方案
- Ubuntu 16.04安装SoapUI工具进行接口测试(Web Service/WSDL/RESTfull)