zoukankan      html  css  js  c++  java
  • 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];
    	}
    };
    
    
  • 相关阅读:
    sqlserver sql优化案例及思路
    mysql执行计划常用说明
    MYSQL 的rownum
    innodb crash
    spring-mybatis源码追踪
    mylyn提交到JIRA的日期格式错误
    [google面试CTCI] 2-1.移除链表中重复元素
    [google面试CTCI] 2-0.链表的创建
    [google面试CTCI] 1-8.判断子字符串
    [google面试CTCI] 1-7.将矩阵中特定行、列置0
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8541953.html
Copyright © 2011-2022 走看看