剑指offer——52.正则表达式匹配
来源:互联网 发布:ubuntu谷歌拼音输入法 编辑:程序博客网 时间:2024/05/22 08:22
题目描述
请实现一个函数用来匹配包括’.’和’‘的正则表达式。模式中的字符’.’表示任意一个字符,而’‘表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串”aaa”与模式”a.a”和”ab*ac*a”匹配,但是与”aa.a”和”ab*a”均不匹配
代码
思路:贪心算法
//s, pattern都是字符串function match(s, pattern){ // write code here if (s == null || pattern == null) { return false; } var str=s.split(''); var pat=pattern.split('') var strIndex = 0; var patternIndex = 0; return matchCore(s, strIndex, pat, patternIndex);}function matchCore(str,strIndex,pattern,patternIndex){ if (strIndex == str.length && patternIndex == pattern.length) { return true; } //pattern先到尾,匹配失败 if (strIndex != str.length && patternIndex == pattern.length) { return false; } //模式第2个是*,且字符串第1个跟模式第1个匹配,分3种匹配模式;如不匹配,模式后移2位 if (patternIndex + 1 < pattern.length && pattern[patternIndex + 1] == '*') { if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) { return matchCore(str, strIndex, pattern, patternIndex + 2)//模式后移2,视为x*匹配0个字符 || matchCore(str, strIndex + 1, pattern, patternIndex + 2)//视为模式匹配1个字符 || matchCore(str, strIndex + 1, pattern, patternIndex);//*匹配1个,再匹配str中的下一个 } else { return matchCore(str, strIndex, pattern, patternIndex + 2); } } //模式第2个不是*,且字符串第1个跟模式第1个匹配,则都后移1位,否则直接返回false if ((strIndex != str.length && pattern[patternIndex] == str[strIndex]) || (pattern[patternIndex] == '.' && strIndex != str.length)) { return matchCore(str, strIndex + 1, pattern, patternIndex + 1); } return false;}
阅读全文
0 0
- 《剑指offer》——正则表达式匹配
- 《剑指offer》——正则表达式匹配
- 剑指offer——正则表达式匹配
- 剑指offer—正则表达式匹配
- 剑指offer—正则表达式匹配
- 剑指offer——52.正则表达式匹配
- 剑指offer-52.正则表达式匹配
- 剑指offer——正则表达式匹配(好题)
- 剑指Offer—52—正则表达式匹配
- 《剑指offer》正则表达式匹配
- 剑指offer--正则表达式匹配
- 剑指offer:正则表达式匹配
- [剑指offer]正则表达式匹配
- 剑指offer-正则表达式匹配
- 剑指offer|正则表达式匹配
- 《剑指offer》-正则表达式匹配
- 剑指offer-正则表达式匹配
- 【剑指offer】正则表达式匹配
- Android:30分钟弄明白Touch事件分发机制
- IOS开发-设置隐藏系统默认返回按钮(默认顶部)
- 浅析java中的BigDecimal
- [JAVA] Hibernate 大数据类型映射
- ESL 7 模型的评估与选择
- 剑指offer——52.正则表达式匹配
- TMS320F2812的CMD文件配置详解
- Git版本回退
- 去掉小数点后多余的Zero
- VIM中正则的非贪婪匹配
- 剑指offer——53.表示数值的字符串
- 1).单例模式的七种写法
- C语言 删除多个相同元素
- Python字符串和编码