Amazon Interview Question
Software Engineer / DevelopersTeam: Chennei
Country: India
Interview Type: Written Test
For simplicity i will consider the following, later can be extended for all:
* --- Matches 0 or more of the preceding char
. --- Matches any single char.
bool matchFirst(const char *str, const char *ptrn){
return ( (*ptrn == *str) ||
(*ptrn == '.' && *str != '\0')
);
}
bool isRegex(const char *str, const char *ptrn) {
//If the Pattern reaches end
if (*ptrn == '\0')
return *str == '\0';
//Case-1: If the Pattern's second char is not *
if (*(ptrn + 1) != '*') {
//If the first char of pattern is "." or first char of pattern == the first i char
//of string, continue to match the left part
if(!matchFirst(str,ptrn))
return false;
return isRegex(str + 1, ptrn + 1);
}
//Case-2: If the Pattern second char is *
else {
//If the first char of pattern is not ".", the first char of pattern and string
//should be the same.
//Else continue to match the rest
if(isRegex(str, ptrn + 2))
return true;
while ( matchFirst(str,ptrn) )
if (isRegex(++str, ptrn + 2))
return true;
}
}
Than you have few months of work until you really give up and start over :)
- arkadi.kagan October 11, 2014Actually, I'd rather build the expression tree first. With expression tree you handle "*", "+", "[]", "()", etc. without redesigning the main loop over and over with each new supported syntax.