Task to be accomplished:
Write a function that takes two strings s and p as arguments and returns a boolean denoting whether s matches p.
p is a sequence of any number of the following:
- a-z - which stands for itself
- . - which matches any character
- * - which matches 0 or more occurrences of the previous single character
Code:
#include <iostream>
using namespace std;
bool eval(string s, string p) {
int j = 0;
for(int i = 0; i < p.length(); i++) {
// is next character is wildcard
if((int)p[i+1] == 42)
{
// is it preceded by a dot
if((int)p[i] == 46)
{
char charToMatch = s[j];
// keep moving forward in string until the repetition of the 'any character' is over
while(s[j] == charToMatch) j++;
}
// it's preceded by a-z
else
{
// keep moving forward in string until repetition of the letter is over
while(s[j] == p[i]) j++;
}
}
// is current character a dot
else if((int)p[i] == 46)
{
// move forward in string as it'll match no matter what
j++;
}
// it's not '.' || '*'
else
{
// is it a-z
if((int)p[i] >= 97 && (int)p[i] <= 122) {
// if current character in string != character mentioned in pattern
if(s[j] != p[i])
{
// pattern doesnt match
return false;
}
else
{
// it matches, move forward
j++;
}
}
}
}
// if pattern is ended but string is still left. pattern didnt match the whole string.
if(j < s.length()) return false;
// gone through whole string, pattern also finished. pattern matches.
else return true;
}
int main() {
cout << eval("a", "b.*"); // false
}
Constraints: Pattern is always valid and non-empty.
I have just started to learn about time complexity of algos and I believe its complexity should be \$\mathcal{O}(nm)\$ where \$n\$ and \$m\$ are the lengths of p and the s respectively.
If it's not please correct me. Along with that, what improvements and optimizations could be made to lower the complexity?