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);
    	}
    }
    
  • 相关阅读:
    Python --- Python的简介
    Python---subline的安装与设置
    算法进阶指南(DFS和BFS)--- 小猫爬山
    算法进阶指南(递归)--- 递归实现排列型枚举
    算法进阶指南(递归)--- 递归实现组合型枚举
    算法进阶指南(递归)--- 递归实现指数型枚举
    linux命令行调试邮件服务器
    01_8_session
    01_7_cookies
    03_9_继承中的构造方法
  • 原文地址:https://www.cnblogs.com/zihaowang/p/4456805.html
Copyright © 2011-2022 走看看