码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][10]Regular Expression Matching解析 -Java实现

时间:2016-06-11 18:57:56      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

Q:

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
A:

以下解法和代码没有借阅以往任何资料,如果有更好的解法请在评论区留言

这道题的大意是实现一个规则表达式的匹配。有两个符号“.”代表任意单个字符”*“代表0或者多个之前的字符。这个我想了想应该可以用队列做,效率也不错。大概画个图表达一下

技术分享

首先可以肯定的是遇到.*这种配合肯定可以直接返回了,而且把a*看成一个字符,或者可以这样说,对比的时候如果字符不一样,规则表达式下一个字符是*则不返回false并且继续判断。如果遇到。则跳过本次判断(需要断定下次不是*)

public class RegularExpressionMatching {
	public static void main(String[] args){
		String s = "abc";
		String reg = "ab*c*";
		System.out.println(method( s, reg));
	}

	private static boolean method(String s, String reg) {
		// TODO Auto-generated method stub
		char[] chars = s.toCharArray();
		char[] charreg = reg.toCharArray();
		char charlast = 0;
		int regIndex = 0;//reg游标
		for(int i =0;i<s.length();i++){//超出游标范围
			if(regIndex>=charreg.length)
				return false;
			
			if(charreg[regIndex]=='.'){//得到。直接跳过
				charlast = charreg[regIndex];
				regIndex++;
				continue;
				
			}else if(charreg[regIndex]=='*'){
				if(regIndex!=0){
					if(charlast=='.')//点星匹配直接返回
						return true;
					else {//星号向下匹配
						int j = i;
						for(;j<s.length();j++){
							if(chars[j]!=charlast)
								break;
						}
						charlast = charreg[regIndex];
						regIndex++;
						i=--j;
						continue;
					}
				}
			}else {//得到字符
				if(chars[i]!=charreg[regIndex]){
					if(regIndex<(charreg.length-1)&&charreg[regIndex+1]=='*'){
						regIndex+=2;
						continue;
					}
					return false;
				}
				if(regIndex<(charreg.length-1)&&charreg[regIndex+1]=='*'){
					charlast = charreg[regIndex];
					i--;
					regIndex++;
					continue;
				}
				regIndex++;
			}
			charlast = charreg[regIndex];
		}
		if(regIndex!=charreg.length)//字长不匹配
		{	if(charreg.length>=regIndex){
				if((regIndex+1)==charreg.length){
					if(charreg[regIndex]!='*')
						return false;
					else
						return true;
				}
				if(charreg[charreg.length-1]!='*')
					return false;
				for(int i = regIndex+2;i<charreg.length;i++){//余下字符都是.*或者char*才行
					if(charreg[i-1]!='.'&&charreg[i-1]!='*'&&charreg[i]!='.'&&charreg[i]!='*'){
						return false;
					}
				}
			}
			return false;
		}
		return true;
	}

由于用了一种笨方法,分叉判断较多可能有误,如果有误请告知,谢谢~也因为这次代码比较杂乱,我可能会跟着有一个改进版,容我最近想想,参考其他篇目。

[LeetCode][10]Regular Expression Matching解析 -Java实现

标签:

原文地址:http://blog.csdn.net/u014629433/article/details/51636454

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!