Recursive function to match a string against a wildcard pattern

后端 未结 4 1626
甜味超标
甜味超标 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:31

    Here is sample solution written in c#. Sorry for lack of comments but I didn't have time for them :/ If you will still need them tomorrow then I can write some, but I hope You will grab the idea.

     public static bool CompareString(string s1, string s2, bool wildCard)
     {
            // Both strings are empty
            if ((s1.Length == 0) && (s2.Length == 0)) return true;
    
            // Second string is empty and there is wildCard character
            if (s2.Length == 0 && wildCard) return true;
    
            //First string is empty. Answer will be true only if all characters in second string are *.
            if (s1.Length == 0 && s2.Length > 0 && s2[0] == '*')
            {
                string newS2 = s2.Remove(0, 1);
                return CompareString(s1, newS2, true);
            }
    
            // One of the strings is empty, and second one is not.
            if (s1.Length * s2.Length == 0) return false;
    
            if (wildCard)
            {
                string newS1 = s1.Remove(0, 1);
                if (CompareString(newS1,s2,true) || CompareString(newS1,s2,false))
                {
                    return true;
                }
            }
            else
            {
                if (s2[0] == '*')
                {
                    string newS2 = s2.Remove(0,1);
                    if (CompareString(s1,newS2,true) || CompareString(s1,newS2,false))
                    {
                        return true;
                    }
                }
                else
                {
                    if (s1[0] == s2[0])
                    {
                        string newS1 = s1.Remove(0,1);
                        string newS2 = s2.Remove(0,1);
                        return CompareString(newS1,newS2,false);
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }
    

提交回复
热议问题