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

    问题描述:

    Implement regular expression matching with support for '.' and '*'.

    '.' Matches any single character.
    '*' Matches zero or more of the preceding element.
    http://i.cnblogs.com/EditPosts.aspx?opt=1
    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

    解题思路:

    从字符串s和p的位置sp,pp处分别开始匹配,运用递归的方法不断缩小字符串的比较长度,最后回溯回来比较结果。

    假设现在走到分别走到sp,pp处。则分为下面几种情况:

    (1)如果pp的位置已经越界,那么若sp也已越界,那么则返回true;否则说明s字符串还有长度,不匹配,返回false;

    (2)pp的位置为p的最后一位,那么此时只能一一匹配,若不匹配则返回false;否则进行下一位比较;

    (3)pp的位置比较靠前,那么比较pp的下一位。如果下一位不是'*',则只能一一匹配,若不匹配则返回false;否则进行下一位比较。如果下一位是'*',则将pp的位置向后移动两位,sp的位置从现在开始进行暴力比较,每次向后移一位进行递归比较。

    代码如下:

    public class Solution {
        public static boolean isMatch(String s, String p) {
    		if (s == null)
    			return p == null;
    		if (p == null)
    			return s == null;
    		return helper(s, p, 0, 0);
    	}
    	private static boolean helper(String s, String p, int sp, int pp) {
    		if (pp >= p.length())
    			return sp >= s.length();
    		// pp comes to end
    		if (pp == p.length() - 1) {
    			if (sp >= s.length()
    					|| (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != '.'))
    				return false;
    			else
    				return helper(s, p, sp + 1, pp + 1);
    		}
    		// p.charAt(pp+1)!='*'
    		if (p.charAt(pp + 1) != '*') {
    			if (sp >= s.length()
    					|| (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != '.'))
    				return false;
    			else
    				return helper(s, p, sp + 1, pp + 1);
    		}
    		// p.charAt(pp+1)=='*'
    		while (sp < s.length()
    				&& (p.charAt(pp) == '.' || s.charAt(sp) == p.charAt(pp))) {
    			if (helper(s, p, sp, pp + 2))
    				return true;
    			sp++;
    		}
    		return helper(s, p, sp, pp + 2);
    	}
    }
    
  • 相关阅读:
    Express请求处理-静态资源的处理
    PostMan怎样携带登录信息请求后台接口防止出现无法访问资源问题
    Express请求处理-GET和POST请求参数的获取
    Express请求处理-构建模块化路由
    Winform中将WebBrower浏览器控件由IE内核修改为Chrome的WebKit内核
    Electron项目怎样打包成桌面exe应用
    Vue项目打包成桌面程序exe除了使用electron-vue你还可以这样
    Vue项目怎样打包并部署在WindowsServer服务器通过IP访问
    Vue本地执行build之后打开dist目录下index.html正常访问
    H5背景音乐
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4456805.html
Copyright © 2011-2022 走看看