Recursive function to match a string against a wildcard pattern

后端 未结 4 2301
长发绾君心
长发绾君心 2021-02-14 20:10

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:30

    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.

提交回复
热议问题