Recursive function to match a string against a wildcard pattern

后端 未结 4 1624
甜味超标
甜味超标 2021-02-14 20:07

So I\'ve been trying to solve this assignment whole day, just can\'t get it.

The following function accepts 2 strings, the 2nd (not 1st) possibly containing *

4条回答
  •  迷失自我
    2021-02-14 20:34

    The problem with your current approach is that it doesn't consider all the possible substrings that a * can match. For example, samePattern("ababababab", "a*b") should return true; the * can match all but the first and last letter of the string, but your code assumes that since the following letter is b, the * matches the empty string.

    I suggest thinking of samePattern as "consuming" its two input strings as it looks for a match. At each step, samePattern should only need to look at the first character of each string to decide whether a match at the first character is possible, and if so make a recursive call to check the rest of the string. The trick will be knowing what to do when you reach a * in the pattern string, since it may or may not be used to match the first character in s1. You shouldn't need to look at the rest of the string to decide what to do.

    Since this is homework, I'll leave figuring out the details of what happens there to you, but hopefully this gets you thinking down the right path.

提交回复
热议问题