通配符匹配 I

1790阅读 0评论2013-10-29 梦醒潇湘love
分类:C/C++


题目描述:
    

解法:
    具体代码如下,其中假设字符串first中没有连续的'*'。
  1. #include <iostream>
  2. using namespace std;

  3. //the main function that checks if two given strings match.
  4. //the first string may contain wildcard characters
  5. bool match(char *first, char *second)
  6. {
  7.     //if we reach at the end of both strings, we are done
  8.     if(*first == '\0' && *second == '\0')
  9.     {
  10.         return true;
  11.     }
  12.     //make sure that the characters after '*' are present in second string
  13.     //The function assumes that the first string will not contain two consecutive '*'
  14.     if(*first == '*' && *(first + 1) != '\0' && *second == '\0')
  15.     {
  16.         return false;
  17.     }

  18.     //if the first string constains '?', or current characters of both strings match
  19.     if(*first == '?' || *first == *second)
  20.     {
  21.         return match(first + 1, second + 1);
  22.     }

  23.     //if there is *, then there are two possibilities
  24.     //a) we consider current character of second string
  25.     //b) we ignore current character of second string
  26.     if(*first == '*')
  27.     {
  28.         return match(first + 1, second) || match(first, second + 1);
  29.     }
  30.     return false;
  31. }

  32. //A function to run test cases
  33. void test(char *first, char *second)
  34. {
  35.     match(first, second)?puts("Yes"):puts("No");
  36. }

  37. int main()
  38. {
  39.     test("g*ks", "geeks");                //yes
  40.     test("ge?ks*", "geeksforgeeks");    //yes
  41.     test("&pqrs", "pqrst");                //no
  42.     return 0;
  43. }

上一篇:Rabin-Karp字符串查找算法
下一篇:通配符匹配II