leetcode 之Implement strStr()(27)

字符串的匹配,返回匹配开始的位置,直接用暴力方式求解。为了更快的匹配,定义一个指针表示待匹配的字符串的长度,当长度不足时,可

直接停止匹配。

char *strStr(char *haystack, char*needle)
      {
          char* p1;
          char* p2;
          char* p1_advance=haystack;

          //当字符串数量不足时,直接停止匹配
          for (p2 = &needle[1]; *p2; p2++)
              p1_advance++;

          for (p1 = haystack; *p1_advance; p1_advance++)
          {
              char *p1_old = p1;
              p2 = needle;
              while (*p1 && *p2 && *p1 == *p2)
              {
                  p1++;
                  p2++;
              }
              if (!*p2)return p1_old;

              p1 = p1_old + 1;
          }

          return nullptr;
      }
View Code

 

posted @ 2016-05-23 12:30  牧马人夏峥  阅读(101)  评论(0编辑  收藏  举报