【leetcode】 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

分析:

除了上面比较基本的情况外,需要考虑的是下面两种情况:

aaaaa,a*a
aa,a*aa

我们很清楚一点就是说:

1.如果字符串s和p,当s[i]==p[j]或者p[j]==.且p[j+1]!='*',我们就比较s[i+1]和p[j+1]

2.如果p[j+1]为*就需要额外考虑。

(a)如果s[i]!=p[j],且p[j+1]=*,则去比较s[i]和p[j+2]

 (b) 如果s[i]==p[j],则返回 s[i+1]与p[j]  || s[i]与p[j+2] 的情况 


附上递归的代码:测试了给的所有案例,全部通过,但是说,如果给的两个字符串太长,会导致TLE。

 public boolean isMatch(String s, String p) {
		 System.out.println("s "+s+" p "+p);
		 if(p==null || p.length()==0)
			 return s.length()==0;
		 if(p.length()>1){
			 if(p.charAt(1)=='*'){
				 if(s==null||s.length()==0)
					 return isMatch(s, p.substring(2));
				 return isMatch(s, p.substring(2))||isMatch(s.substring(1),p );
			 }else{
				 if(s==null||s.length()==0)
					 return false;
				 if(s.charAt(0)==p.charAt(0) || p.charAt(0)=='.')
					 return isMatch(s.substring(1), p.substring(1));
			 }
		 }else if(p.length()==1){
			 if(p.charAt(0)=='.'){
				 if(s==null||s.length()<=1)
					 return true;
				 else
					 return false;
			 }else{
				 if(s==null||s.length()==0||s.length()>1)
					 return false;
				 return s.charAt(0)==p.charAt(0);
			 }
		 }
		return false;
	 }


我们已经知道,出现超时的原因就是太多的递归,现在我们从减少递归入手:

public 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 len = s.length();
	 
	            int i = -1; 
	            while(i<len && (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;
	        } 
	    }


展开阅读全文

Pattern Matching Using Regular Expression

02-22

A regular expression is a string which contains some normal characters and some meta characters. The meta characters include,n. means any characternn[c1-c2] means any character between c1 and c2 (c1 and c2 are two characters)nn[^c1-c2] means any character not between c1 and c2 (c1 and c2 are two characters)nn* means the character before it can occur any timesnn+ means the character before it can occur any times but at least one timesnn\ means any character follow should be treated as normal characternYou are to write a program to find the leftmost substring of a given string, so that the substring can match a given regular expression. If there are many substrings of the given string can match the regular expression, and the left positions of these substrings are same, we prefer the longest one.nnnInputnnEvery two lines of the input is a pattern-matching problem. The first line is a regular expression, and the second line is the string to be matched. Any line will be no more than 80 character. A line with only an "end" will terminate the input.nnnOutputnnFor each matching problem, you should give an answer in one line. This line contains the string to be matched, but the leftmost substring that can match the regular expression should be bracketed. If no substring matches the regular expression, print the input string.nnnSample Inputnn.*nasdfnf.*d.nsefdfsden[0-9]+nasd345dsfn[^\*-\*]n**asdf**fasdnb[a-z]*r[s-u]*nabcdefghijklmnopqrstuvwxyzn[T-F]ndfkgjfnendnnnSample Outputnn(asdf)nse(fdfsde)nasd(345)dsfn**(a)sdf**fasdna(bcdefghijklmnopqrstu)vwxyzndfkgjf 问答

没有更多推荐了,返回首页