Regular Expression Matching
2015-10-08 21:44
337 查看
正则匹配
Regular Expression Matching
Implement regular expression matching with support for
输出:
false
true
true
false
false
abcdefg
Regular Expression Matching
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
package com.rust.TestString; class Solution { public boolean isMatch(String s, String p) { if (p.length() == 0) { return s.length() == 0; } if (p.length() == 1) { return (s.length() == 1) && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'); } // next char is not '*': must match current character if (p.charAt(1) != '*') { if (s.length() == 0) { return false; } else { return (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && isMatch(s.substring(1), p.substring(1)); // judge next char } } else { // next char is '*' while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) { if (isMatch(s, p.substring(2))) { return true; } s = s.substring(1); } return isMatch(s, p.substring(2)); } } } public class RegularExpressionMatching { public static void main(String args[]){ Solution solution = new Solution(); String s = "abcdefg"; System.out.println(solution.isMatch(s, "abcde*")); System.out.println(solution.isMatch(s, ".*")); System.out.println(solution.isMatch("abcdefg", "a.*")); System.out.println(solution.isMatch("abcdefg", ".b.")); System.out.println(solution.isMatch("abcdefg", "")); System.out.println(s); } }
输出:
false
true
true
false
false
abcdefg
相关文章推荐
- 026-代码创建控件-iOS笔记
- C++ 面试 (1) 指针
- 08-DOM操作多选下拉列表
- EffectiveC#6--区别值类型数据和引用类型数据
- Testlink的使用
- 一种全新的截屏方法
- Unity协程(Coroutine)原理深入剖析
- java选择题
- 设计模式之建造者模式
- 策略模式学习笔记
- 024-Foundation框架(下)-OC笔记
- 023-Foundation框架(上)-OC笔记
- Java体系结构简介
- 数据库操作失败就【回滚】
- 高项2015年下半年培训随堂作业(10月10日)
- Oracle-卸载
- Nginx介绍及企业web服务软件选择
- Oracle-简介
- 更改dedecms单页模块生成目录和链接的方法
- 寻找第K大元素的八大算法、源码及拓展