Interview Questions

172. Write a function which determines whether provided string matches specified pattern .......

Microsoft Interview Questions and Answers


(Continued from previous question...)

172. Write a function which determines whether provided string matches specified pattern .......

Question:
Write a function which determines whether provided string matches specified pattern.
Signature:
bool is_match(char* text, char* pattern)

Pattern can contain any characters + '*' character which means zero or more characters. For example: is_match("hello", "h*o") returns true; is_match("hello", "hel*lo") also returns true.


maybe an answer:


bool is_match(const char * text, const char * pattern)
{
const char equal_char = '@';

size_t text_len = strlen(text);
if(!text_len)
throw std::invalid_argument("wrong text`s length");

size_t patt_len = strlen(pattern);
if(!patt_len)
throw std::invalid_argument("wrong pattern`s length");

if(strchr(pattern, '*') == NULL)
throw std::invalid_argument("pattern has no \"*\"");

char * compare_str;

if(text_len >= patt_len)
{
compare_str = new char[text_len];

if(pattern[0] == '*') {
int i = text_len - 1, j = patt_len - 1;
while(pattern[j] != '*')
compare_str[i--] = pattern[j--];

memset(compare_str, equal_char, i + 1);
}
else if (pattern[patt_len - 1] == '*') {
int i = 0;
while(pattern[i] != '*')
compare_str[i] = pattern[i++];

memset(compare_str + i, equal_char, text_len - i);
}
else {
int i = 0;
while(pattern[i] != '*')
compare_str[i] = pattern[i++];

int j = text_len - 1;
int k = patt_len - 1;
while(pattern[k] != '*')
compare_str[j--] = pattern[k--];

memset(compare_str + i, equal_char, j - i + 1);

}
}
else
{
int i = 0, j = 0;
compare_str = new char[patt_len];
while(pattern[i])
{
if(pattern[i] != '*')
compare_str[j++] = pattern[i];
++i;
}
}

for(int i = 0; i < text_len; ++i)
{
if(text[i] == compare_str[i] || compare_str[i] == equal_char)
continue;

delete[] compare_str;
return false;
}

delete[] compare_str;
return true;
}

(Continued on next question...)

Other Interview Questions