LeetCode - #10 regular expression matching (top 100)

Posted by cohq82 on Mon, 03 Jan 2022 22:09:40 +0100

preface

This topic is the top 100 high frequency questions of LeetCode

Our community will gradually organize the Swift Algorithm Solutions of Gu Yi (Netflix growth hacker, author of iOS interview, ACE professional fitness coach. Microblog: @ Taoist Gu Yin) into text versions to facilitate everyone's learning and reading.

So far, we have updated 9 issues of LeetCode algorithm. We will keep the update time and progress (released at 9:00 a.m. on Monday, Wednesday and Friday). There is not much content in each issue. We hope you can read it on the way to work and the long-term accumulation will be greatly improved.

Little steps, no even thousands of miles; If you don't accumulate small streams, you can't become a river and sea. Swift community will accompany you forward. If you have any suggestions and comments, please leave a message at the end of the article. We will try our best to meet your needs.

Difficulty level: difficulty

1. Description

Given a string s and a character rule p, please implement a support '.' Matches the regular expression of '*'.

  • '.' matches any single character
  • '*' matches zero or more preceding elements

The so-called matching is to cover the whole string s, not part of the string.

2. Examples

Example 1

Input: s = "aa" p = "a"
Output: false
 Explanation:"a" Cannot match "aa" The entire string.

Example 2

Input: s = "aa" p = "a*"
Output: true
 Explanation: because '*' Represents the one that can match zero or more preceding elements, The preceding element here is 'a'. Therefore, the string "aa" Can be considered 'a' Again.

Example 3

Input: s = "ab" p = ".*"
Output: true
 Explanation:".*" Indicates that zero or more can be matched('*')Any character('.'). 

Example 4

Input: s = "aab" p = "c*a*b"
Output: true
 Explanation: because '*' Represents zero or more, here 'c' Is 0, 'a' Be repeated once. So you can match strings "aab". 

Example 5

Input: s = "mississippi" p = "mis*is*p*."
Output: false

Constraints:

  • 1 <= s.length <= 20
  • 1 <= p.length <= 30
  • s may be empty and contain only lowercase letters from a-z.
  • p may be empty and contain only lowercase letters from a-z and characters And *.
  • Ensure that every time the character * appears, it is preceded by a valid character

3. Answer

class RegularExpressionMatching {
    func isMatch(_ s: String, _ p: String) -> Bool {
        let sChars = Array(s), pChars = Array(p)
        var dp = Array(repeating: Array(repeating: false, count: pChars.count + 1), count: sChars.count + 1)
        dp[0][0] = true
        
        for i in 0...pChars.count {
        	// jump over "" vs. "x*" case
            dp[0][i] = i == 0 || i > 1 && dp[0][i - 2] && pChars[i - 1] == "*"
        }
        
        for i in 0...sChars.count {
            for j in 0...pChars.count {
                guard j > 0 else {
                    continue
                }
                
                let pCurrent = pChars[j - 1]
                
                if pCurrent != "*" {
                    dp[i][j] = i > 0 && dp[i - 1][j - 1] && (pCurrent == "." || pCurrent == sChars[i - 1])
                } else {
                    dp[i][j] = dp[i][j - 2] || i > 0 && j > 1 && (sChars[i - 1] == pChars[j - 2] || pChars[j - 2] == ".") && dp[i - 1][j]
                }
            }
        }
        
        return dp[sChars.count][pChars.count]
    }
}
  • Main idea: classical two-dimensional dynamic programming
  • Time complexity: O(mn)
  • Space complexity: O(mn)

The warehouse of the algorithm solution: LeetCode-Swift

go to LeetCode practice

Previous review

There are 5 high-frequency questions in the published articles

LeetCode - #1 sum of two numbers

Difficulty level: easy. The frequency of company interview is as follows:

companyfrequency
Amazon★★★★★★
Facebook★★★★★
Airbnb★★★★★
Microsoft★★★★★
LinkedIn★★★★

LeetCode - #2 adding two numbers

Difficulty level: medium. The frequency of company interview is as follows:

companyfrequency
Microsoft★★★★
Amazon★★
Airbnb★★

LeetCode - #3 longest unrepeated substring

Difficulty level: medium. The frequency of company interview is as follows:

companyfrequency
Amazon★★

LeetCode - #4 find the middle value of two ordered arrays

Difficulty level: difficulty

LeetCode - #5 find the longest image string

Difficulty level: medium. The frequency of company interview is as follows:

companyfrequency
Amazon★★

Difficulty level: easy, medium, difficult
Company use frequency: 1 ~ 6 ★

About us

We are jointly maintained by Swift enthusiasts. We will share the technical content with Swift actual combat, Swift UI and Swift foundation as the core, and also sort out and collect excellent learning materials.

Later, we will translate a lot of data to our official account. Interested friends can join us.

Topics: Algorithm leetcode regex