Determining if a string matches a specific pattern

I recently had an interview with Google for the position of Software Engineering, and the question asked was seen as creating a template.

So you have to create

boolean isPattern(String givenPattern, String stringToMatch)

A function that performs the following actions:

givenPattern is a string containing:

a) 'a'-'z' chars
b) '*' chars which can be matched by 0 or more letters
c) '?' which just matches to a character - any letter basically

So the call may be something like

isPattern("abc", "abcd") - returns false, because it does not match the pattern ('d' is optional)

isPattern("a*bc", "aksakwjahwhajahbcdbc")which is true, since we have "a" at the beginning, many characters after and then end with "bc"

isPattern("a?bc", "adbc") returns true because each character in the pattern matches the given string.

, , , , , , * ? . for-loops, 45 .

-, , , ?

!

+5
2
boolean isPattern(String givenPattern, String stringToMatch) {
    if (givenPattern.empty)
        return stringToMatch.isEmpty();
    char patternCh = givenPatter.charAt(0);
    boolean atEnd = stringToMatch.isEmpty();
    if (patternCh == '*') {
        return isPattenn(givenPattern.substring(1), stringToMatch)
            || (!atEnd && isPattern(givenPattern, stringToMatch.substring(1)));
    } else if (patternCh == '?') {
        return !atEnd && isPattern(givenPattern.substring(1), 
            stringToMatch.substring(1));
    }
    return !atEnd && patternCh == stringToMatch.charAt(0)
          && isPattern(givenPattern.substring(1), stringToNatch.subtring(1);
}

( .)

+3

, , - :

static boolean isPattern(String givenPattern, String stringToMatch) {
    String regex = "^" + givenPattern.replace("*", ".*").replace("?", ".") + "$";

    return Pattern.compile(regex).matcher(stringToMatch).matches();
}

"^" -
"$" -
. " ", .* " ", 0

. * ? , [a-zA-Z] ..

+6

All Articles