zoukankan      html  css  js  c++  java
  • [leetcode]Regular Expression Matching

    此题有难度。一开始是用循环往前p和s贪心来做,代码已经很复杂,但处理依然有(大)错。如 aaab配a*ab 和 babc配.*c的情况无法处理。看了网上的资料后才认定这种情况必须要全面回溯匹配,这种情况下最适合的就是递归了。默默的写程序,中间有漏过*s!=0的判断,但几次修改后居然通过了,小激动。

    参考:http://discuss.leetcode.com/questions/175/regular-expression-matching

    class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function    
            if (*p == 0) return *s == 0;
        	if (*(p+1) != '*')
    		{
    			if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s+1, p+1);
    			else return false;
    		}
    		else
    		{
    			// *s == *p
    			while (*s != 0 && (*s == *p || *p == '.'))
    			{
    				if (isMatch(s, p+2)) return true;
    				s++;
    			}
    			return (isMatch(s, p+2));
    		}
        }
    };
    

    Another:

    class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            if (*p == '') {
                return *s == '';
            }
            if (*s != '' && (*s == *p || *p == '.')) {
                if (*(p+1) == '*') {
                    return isMatch(s, p+2) || isMatch(s+1, p);
                } else {
                    return isMatch(s+1, p+1);
                }
            }
            if (*(p+1) == '*') {
                return isMatch(s, p+2);
            } else {
                return false;
            }
        }
    };
    

      

  • 相关阅读:
    通用sqlserver分页存储过程
    JSONP解决跨域请求
    laravle框架
    XML作用
    mysql 中的常用查询
    smarty模板技术
    Cookie和Session 会话技术
    正则表达式
    Mongodb常用知识点
    PHP之PDO
  • 原文地址:https://www.cnblogs.com/lautsie/p/3217563.html
Copyright © 2011-2022 走看看