Regular Expression Matching(LeedCode)

正则匹配字符串

Question:

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

Subscribe to see which companies asked this question.

在题目中“.”表示可以匹配任意一个字符,“*”表示可以匹配在他之前的那个字符可以有任意多个。例如”a*b”->”aaaaaab”;
* 当p.length==0时,判断s.lenght==0?true:false;
* 当p.length==1时,判断s.charAt(0) == p.charAt(0) || (p.charAt(0) == ‘.’ && s.length == 1)?true:false;
* 当p.length>1时,我们可以使用递归来判断s与p是否匹配!

import java.util.Scanner;

public class Solution {

    public static boolean isMatch(String s, String p) {
        //正则表达式匹配(“.”只能匹配单个字符,“*”可以匹配之前的多个元素)
        int lenP = p.length();
        int lenS = s.length();
        //如果p的长度为0的话, 判断s的长度是否为零
        if(lenP==0){
            return lenS == 0;
        }
        if(lenP == 1){
            if(p.equals(s) || p.equals(".") && lenS == 1){
                return true;
            }
            return false;
        }

        if(p.charAt(1) != '*'){
            //如果字符串p.charAt(1)!='*',我们则递归的削减字符串s和p的第一个字符来判断两者是否相同
            if(lenS > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
                return isMatch(s.substring(1), p.substring(1));
            }
            return false;
        }else{
            //如果字符串p.charAt(1)=='*',我们则要递归的判断s[0……s.length-1]与p[2……p.length-1]
            while(s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){
                if(isMatch(s, p.substring(2))){
                    return true;
                }
                s = s.substring(1);
            }
            return isMatch(s, p.substring(2));
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        System.out.println(isMatch(s1, s2));
        in.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值