Skip to content

Commit 8362a50

Browse files
Refactor code to address codacy comments
1 parent 39fc55a commit 8362a50

File tree

1 file changed

+37
-16
lines changed

1 file changed

+37
-16
lines changed

Algorithms/Strings/PatternMatching/WildCardMatcher.cs

Lines changed: 37 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -52,25 +52,46 @@ public static bool MatchPattern(string inputString, string pattern)
5252
{
5353
for (var j = 1; j < patternLength; j++)
5454
{
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);
7156
}
7257
}
7358

7459
return dp[inputLength - 1, patternLength - 1];
7560
}
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+
}
7697
}

0 commit comments

Comments
 (0)