leetcode 10
Posted ondaytobewhoyouwant
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 10相关的知识,希望对你有一定的参考价值。
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 lettersa-z
.p
could be empty and contains only lowercase lettersa-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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode刷题Python LeetCode 2038. 如果相邻两个颜色均相同则删除当前颜色
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段