• 44. Wildcard Matching


    44. Wildcard 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
    

    解析

    
    直接用递归会超时,这里用到了回溯的思想。
     
    '?' 比较好处理,++i,++j 即可
     
    关键是 '*' ,这里定义了 i 和 j 的回溯点:
    每当遇到 '*' 时,
    记录 i 的回溯点 i_recall = i;
    记录 j 的回溯点 j_recall = ++j,这里选择 j 自增后的位置,因为此时 j 为 '*',尝试用后面的模式来匹配该元素。
     
    当遇到不能匹配的点时,就会进入到第 3 个 if,此时把 i 回溯到 i_recall 后,同时 i_recall 自增,j 回溯到 j_recall,表示将原来记录的回溯点用 '*' 来匹配,再重新做这一轮的匹配。
     
    最后要把末尾的 '*' 都忽略,若 p[j] 为空则代表匹配完成,若还有剩余元素说明不匹配。
    
    // add 44. Wildcard Matching
    class Solution_44 {
    public:
    	bool isMatch(string s, string p) {
    		int i = 0, j = 0, j_recall = 0, i_recall = 0;
    		while (s[i]) {
    			if (p[j] == '?' || s[i] == p[j])
    			{
    				++i; ++j; continue;
    			}
    			if (p[j] == '*')
    			{
    				i_recall = i; j_recall = ++j; continue;
    			}
    			if (j_recall)
    			{
    				i = ++i_recall; j = j_recall; continue;
    			}
    			return
    				false;
    		}
    		while (p[j] == '*')
    			++j;
    		return !p[j];
    	}
    };
    
    
  • 相关阅读:
    使用 Docker 安装 Jenkins 的最佳方式
    使用 Docker 在 Linux 上托管 ASP.NET Core 应用程序
    分布式缓存 Redis 集群搭建
    [译]RabbitMQ教程C#版
    如何解决 React 官方脚手架不支持 Less 的问题
    [译]RabbitMQ教程C#版
    [译]RabbitMQ教程C#版
    快速签发 Let's Encrypt 证书指南
    [译]RabbitMQ教程C#版
    [译]RabbitMQ教程C#版
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8541953.html
Copyright © 2020-2023  润新知