动态规划动态规划

Regular Expression Matching go语言

2018-09-22  本文已影响0人  fjxCode

Regular Expression Matching

题目描述

Given an input string (s) and a pattern (p), 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).

Note:

s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.

思路:

细节:

解:

package main

import "fmt"

func isMatch(s string, p string) bool {
    sSlice := []rune(s)
    pSlice := []rune(p)
    dp := make([][]bool,len(s)+1)
    for idx,_ := range dp{
        dp[idx] = make([]bool,len(p)+1)
    }
    dp[0][0] = true
    for i:=0;i<len(p);i++ {
        if pSlice[i] == '*' {
            dp[0][i+1] = dp[0][i-1]
        }
    }
    for i:=0;i<len(s);i++{
        for j:=0;j<len(p);j++{
            if  pSlice[j] == '.' || pSlice[j] == sSlice[i]{
                dp[i+1][j+1] = dp[i][j]
            }
            if pSlice[j] == '*'{
                if pSlice[j-1] == '.' || pSlice[j-1] == sSlice[i]{
                    //a*匹配1个或多个
                    dp[i+1][j+1] = dp[i+1][j]|| dp[i][j+1]||dp[i+1][j-1]
                }else if j>0 {
                    dp[i+1][j+1] = dp[i+1][j-1]
                }
            }
        }
    }
    return dp[len(s)][len(p)]
}

func main()  {
    s := ""
    p := ".*"
    res := isMatch(s, p)
    fmt.Print(res)
}
上一篇 下一篇

猜你喜欢

热点阅读