LeetCode正则表达式-Regular Expression Matching

前端之家收集整理的这篇文章主要介绍了LeetCode正则表达式-Regular Expression Matching前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Implement regular expression matching with support for'.'and'*'.

  1. '.' Matches any single character.
  2. '*' Matches zero or more of the preceding element.
  3.  
  4. The matching should cover the entire input string (not partial).
  5.  
  6. The function prototype should be:
  7. bool isMatch(const char *s,const char *p)
  8.  
  9. Some examples:
  10. isMatch("aa","a") false
  11. isMatch("aa","aa") true
  12. isMatch("aaa","aa") false
  13. isMatch("aa","a*") true
  14. isMatch("aa",".*") true
  15. isMatch("ab",".*") true
  16. isMatch("aab","c*a*b") true
  1. public boolean isMatch(String s,String p) {
  2. 	if(p.length()==0||p==null){
  3. 		return s==null||s.length()==0;
  4. 	}
  5. 	if(s==null){
  6. 		return false;
  7. 	}
  8. 	if(s.length()==0){
  9. 		if(p.length()%2==1)
  10. 			return false;
  11. 		else{
  12. 			for(int i=0;i<p.length();i++){
  13. 				if(i%2==1&&p.charAt(i)!='*'){
  14. 					return false;
  15. 				}
  16. 			}
  17. 			return true;
  18. 		}
  19. 	}
  20. 	if(p.length() == 1){
  21. 		if(s.length()>1){
  22. 			return false;
  23. 		}
  24. 		if(p.charAt(0) == s.charAt(0)||p.charAt(0)=='.'){
  25. 			return true;
  26. 		}
  27. 		return false;
  28. 	}
  29. 	else{
  30. 		if(p.charAt(1)=='*'){
  31. 			while(s.length()!=0&&(p.charAt(0)==s.charAt(0)||p.charAt(0)=='.')){
  32. 				if(isMatch(s,p.substring(2))){
  33. 					return true;
  34. 				}
  35. 				s = s.substring(1);
  36. 			}
  37. 			return isMatch(s,p.substring(2));
  38. 		}
  39. 		else{
  40. 				if(p.charAt(0)==s.charAt(0)||p.charAt(0)=='.'){
  41. 					return isMatch(s.substring(1),p.substring(1));
  42. 				}
  43. 				return false;
  44. 		}
  45. 	}
  46. }

    基本思想就是:回溯法,对于'*'和它之前的字符t(可以是任意字符)组成的元组,s中的t可以使用p中的t*来匹配,也可以不使用,如果不使用,就isMatch(s,p.substring(2))利用p后面的来匹配t,如果后面的不能匹配,就将s=s.substring(1),这句话就相当于使用了t*来匹配t然后继续判断是否进入while循环

猜你在找的正则表达式相关文章