@@ -52,25 +52,46 @@ public static bool MatchPattern(string inputString, string pattern)
52
52
{
53
53
for ( var j = 1 ; j < patternLength ; j ++ )
54
54
{
55
- // If the characters match or the pattern has a ., then the result is the same as the previous positions.
56
- if ( inputString [ i - 1 ] == pattern [ j - 1 ] || pattern [ j - 1 ] == '.' )
57
- {
58
- dp [ i , j ] = dp [ i - 1 , j - 1 ] ;
59
- }
60
- else if ( pattern [ j - 1 ] == '*' )
61
- {
62
- if ( dp [ i , j - 2 ] )
63
- {
64
- dp [ i , j ] = true ;
65
- }
66
- else if ( inputString [ i - 1 ] == pattern [ j - 2 ] || pattern [ j - 2 ] == '.' )
67
- {
68
- dp [ i , j ] = dp [ i - 1 , j ] ;
69
- }
70
- }
55
+ MatchRemainingLenghts ( inputString , pattern , dp , i , j ) ;
71
56
}
72
57
}
73
58
74
59
return dp [ inputLength - 1 , patternLength - 1 ] ;
75
60
}
61
+
62
+ // Helper method to match the remaining lengths of the input string and the pattern
63
+ // This method is called for all i and j where i > 0 and j > 0
64
+ private static void MatchRemainingLenghts ( string inputString , string pattern , bool [ , ] dp , int i , int j )
65
+ {
66
+ // If the characters match or the pattern has a ., then the result is the same as the previous positions.
67
+ if ( inputString [ i - 1 ] == pattern [ j - 1 ] || pattern [ j - 1 ] == '.' )
68
+ {
69
+ dp [ i , j ] = dp [ i - 1 , j - 1 ] ;
70
+ }
71
+ else if ( pattern [ j - 1 ] == '*' )
72
+ {
73
+ MatchForZeroOrMore ( inputString , pattern , dp , i , j ) ;
74
+ }
75
+ else
76
+ {
77
+ // If the characters do not match, then the result is false, which is the default value.
78
+ }
79
+ }
80
+
81
+ // Helper method to match for the "*" pattern.
82
+ private static void MatchForZeroOrMore ( string inputString , string pattern , bool [ , ] dp , int i , int j )
83
+ {
84
+ if ( dp [ i , j - 2 ] )
85
+ {
86
+ dp [ i , j ] = true ;
87
+ }
88
+ else if ( inputString [ i - 1 ] == pattern [ j - 2 ] || pattern [ j - 2 ] == '.' )
89
+ {
90
+ dp [ i , j ] = dp [ i - 1 , j ] ;
91
+ }
92
+ else
93
+ {
94
+ // Leave the default value of false
95
+ }
96
+ }
76
97
}
0 commit comments