-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathpatternMatch.go
More file actions
executable file
·80 lines (68 loc) · 2.16 KB
/
patternMatch.go
File metadata and controls
executable file
·80 lines (68 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright 2021 American Express
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package wildcard
import "strings"
func initLookupTable(row, column int) [][]bool {
lookup := make([][]bool, row)
for i := range lookup {
lookup[i] = make([]bool, column)
}
return lookup
}
//PatternMatch Function that matches input str with given wildcard pattern
func PatternMatch(str, pattern string) bool {
s := []rune(strings.ToLower(str))
p := []rune(strings.ToLower(pattern))
// empty pattern can only match with empty string
if len(p) == 0 {
return len(s) == 0
}
// lookup table for storing results of subproblems
// zero value of lookup is false
lookup := initLookupTable(len(s)+1, len(p)+1)
// empty pattern can match with empty string
lookup[0][0] = true
// Only '*' can match with empty string
for j := 1; j < len(p)+1; j++ {
if p[j-1] == '*' {
lookup[0][j] = lookup[0][j-1]
}
}
// fill the table in bottom-up fashion
for i := 1; i < len(s)+1; i++ {
for j := 1; j < len(p)+1; j++ {
if p[j-1] == '*' {
// Two cases if we see a '*'
// a) We ignore ‘*’ character and move
// to next character in the pattern,
// i.e., ‘*’ indicates an empty sequence.
// b) '*' character matches with ith
// character in input
lookup[i][j] = lookup[i][j-1] || lookup[i-1][j]
} else if p[j-1] == '?' || s[i-1] == p[j-1] {
// Current characters are considered as
// matching in two cases
// (a) current character of pattern is '?'
// (b) characters actually match
lookup[i][j] = lookup[i-1][j-1]
} else {
// If characters don't match
lookup[i][j] = false
}
}
}
return lookup[len(s)][len(p)]
}