【leetcode刷题笔记】Regular Expression 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


题解:又见递归的解法。这道题交了好多次,主要是细节要想清楚。总结一下要注意的地方:

  • s为0的时候,如果p为1,false;否则如果p的第1位上为‘*‘,那么就要考察p后面的元素,于是递归调用 isMatch(s, p.substring(2)) ,这样的例子有s = "", p = "c*c*";如果p的第一位上不为1,那么s和p肯定不匹配了。
  • 当p长度为1的时候要单独处理,因为这时候我们不用判断p的第1位是否是‘*’了。处理这一段代码如下:
  1. if(p.length() == 1){
            if(p.charAt(0) == ‘.‘ && s.length() == 1)
                return true;
            return s.equals(p);
    }
  • 其他情况就要按照p的第1位是否为‘*‘来分了。如果不为’*‘,那么p和s的第0位必须匹配(相等或p第0位为‘.‘),否则p和s不匹配,这样的例子类似的有s = "ab", p = "c*b"。如果为‘*‘,我们就按照匹配0位,1位,2位.....的方式递归试探,类似的例子有s = "abbc", p = "ab*bbc",此时‘*‘并不匹配s中的任何字符,再有s = "aa",p = "a*",此时‘*‘匹配s中的两个a。

代码如下:

 1 public class Solution {
 2     public boolean isMatch(String s, String p) {
 3          if(p.length() == 0)
 4             return s.length() == 0;
 5
 6         if(s.length() == 0){
 7             if(p.length() == 1)
 8                 return false;
 9             if(p.charAt(1) == ‘*‘)
10                 return isMatch(s, p.substring(2));
11             return false;
12         }
13
14
15         if(p.length() == 1){
16             if(p.charAt(0) == ‘.‘ && s.length() == 1)
17                 return true;
18             return s.equals(p);
19         }
20
21         if(p.length() >= 2 && p.charAt(1) != ‘*‘){
22             //if p(1) is not *, we need p(0) equals to s(0) or p(0) equals ‘.‘
23             if(p.charAt(0) == s.charAt(0) || p.charAt(0) == ‘.‘ && s.length() != 0)
24                 //check if the left is also match
25                 return isMatch(s.substring(1), p.substring(1));
26             return false;
27         }
28         else{
29             //if p(1) is ‘*‘,we check how many we can match from this * by trying
30             int i = 0;
31             char now = p.charAt(0);
32             while(i<s.length() && (s.charAt(i) == now || now == ‘.‘)){
33                 if(isMatch(s.substring(i+1),p.substring(2)))
34                         return true;
35                 i++;
36             }
37             //this means we don‘t use this ‘*‘ to match any character, just skip it
38             return isMatch(s, p.substring(2));
39         }
40     }
41 }

【leetcode刷题笔记】Regular Expression Matching

时间: 2025-01-18 09:07:55

【leetcode刷题笔记】Regular Expression Matching的相关文章

【leetcode刷题笔记】Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function p

刷题10. Regular Expression Matching

一.题目说明 这个题目是10. Regular Expression Matching,乍一看不是很难. 但我实现提交后,总是报错.不得已查看了答案. 二.我的做法 我的实现,最大的问题在于对.*的处理有问题,始终无法成功. #include<iostream> using namespace std; class Solution{ public: bool isMatch(string s,string p){ bool result = true; if(s.length()<=0

【leetcode刷题笔记】Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -&g

【leetcode刷题笔记】Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

【leetcode刷题笔记】Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example,Given [100, 4, 200, 1, 3, 2],The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in

【leetcode刷题笔记】Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For example,Given sorted array A = [1,1,1,2,2,3], Your function should return length = 5, and A is now [1,1,2,2,3]. 题解: 设置两个变量:右边kepler和前向游标forward.如果当前kepeler所指的元素和

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true, as t

【leetcode刷题笔记】Insertion Sort List

Sort a linked list using insertion sort. 题解:实现链表的插入排序. 要注意的地方就是,处理链表插入的时候尽量往当前游标的后面插入,而不要往前面插入,后者非常麻烦.所以每次利用kepeler.next.val和head.val比较大小,而不是kepeler.val和head.val比较大小,因为如果用后者,要把head指向的节点插入到kepeler指向的节点的前面,如果kepeler指向的节点是头结点,就更麻烦了. 代码如下: 1 /** 2 * Defi