码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 10

时间:2018-10-04 23:53:02      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:empty   tco   ring   lse   etc   .com   代码   ane   cti   

10. Regular Expression Matching

Given an input string (s) and a pattern (p), 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).

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: ‘*‘ means zero or more of the precedeng element, ‘a‘. Therefore, by repeating ‘a‘ once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

题意分析,这是一道字符串匹配的题目,*可以多次或者零次替换为前面的字符。‘.‘可以匹配一次任意字符。
解体的思路,从左向右扫描字符串,考虑两种特殊的情形,一种是p为空串,和p的长度是1,如果p长度是2,则分为
有没有 *的出现在第二位,如果没有的话,则整个的字符串匹配等价于,第一个字符匹配并且后面的字符满足通配形式。
如果有 *号出现的话,则需要在不影响后面能否匹配的条件下,一直选择通配,直到不能再匹配为止。

具体的代码如下:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    bool isMatch(string s, string p) {
        // cout << s <<  "      "<< p << endl;
        if(p.empty())return s.empty();
        if(p.size() == 1)
        {
        	return (s.size() == 1 && (s[0] == p[0]||p[0] == ‘.‘));
		}
		if(p[1] !=‘*‘)return !s.empty()&&(s[0] == p[0]||p[0] == ‘.‘)&&isMatch(s.substr(1),p.substr(1));
		//现在p[1] == ‘*‘;
		while(!s.empty() && (p[0] ==  s[0] || p[0] == ‘.‘))
		{
			if(isMatch(s, p.substr(2)) )return true;
			s = s.substr(1);
		 } 
		 return isMatch(s,p.substr(2));
    }
};

  总结:需要对于一个问题有比较合理的分类讨论的能力,并且需要清楚*到底有什么用。

 

leetcode 10

标签:empty   tco   ring   lse   etc   .com   代码   ane   cti   

原文地址:https://www.cnblogs.com/ondaytobewhoyouwant/p/9743712.html

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