10. Regular Expression Matching (JAVA)
Given an input string (s) and a pattern (p), 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
class Solution {
public boolean isMatch(String s, String p) {
return recur(s,p,0,0);
} public boolean recur(String s, String p, int sPtr, int pPtr) {
if(s.length() == sPtr && p.length() == pPtr) return true;
if(p.length() == pPtr) return false;
if(s.length() == sPtr){
if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*') return recur(s,p,sPtr,pPtr+2);
else return false;
} if(p.length() > pPtr+1 && p.charAt(pPtr+1)=='*'){ //next bit is *
if(recur(s,p,sPtr,pPtr+2)) return true; //* match 0 element
else{
for(int i = 1; sPtr + i <= s.length() && (p.charAt(pPtr)==s.charAt(sPtr+i-1)|| p.charAt(pPtr)=='.'); i++){
if(recur(s,p,sPtr+i,pPtr+2)) return true; //* match i elements
}
}
}
else if(p.charAt(pPtr)=='.' || p.charAt(pPtr)==s.charAt(sPtr))
return recur(s, p, sPtr+1, pPtr+1); return false;
}
}
当当前字符之后的那个字符是*时,我们需要对当前字符做特别判断,所以没次递归中要判断p字符串的下一个字符是否是*
最新文章
- [Xilinx]Modelsim独立仿真Vivado生成的PLL核
- SQL Server日期和时间的格式
- consul的安装配置 一centos7环境
- Multi-source Replication
- 深入学习:如何实现不同Android设备之间相同应用程序的网络服务发现功能
- 神奇的脱机 app_offline.htm
- spring4 定时任务
- void指针、NULL指针和未初始化指针
- eclipse tomcat内存溢出,加大内存
- 关于Mongdb的java的CRUD操作
- java返回数据工具类
- pycharm中replace的应用
- Request method &#39;POST&#39; not supported错误和解决方法
- printf scanf cin cout的区别与特征
- VUE2.0 饿了吗视频学习笔记(三):VUE2.0取消了v-link
- 解释器模式 Interpreter
- 基于Windows 机器学习(Machine Learning)的图像分类(Image classification)实现
- winform界面开发-HTML内容编辑控件
- Atitit.注解解析(1)---------词法分析 attilax总结 java .net
- java通过ping 判断网络是否正常