zoukankan      html  css  js  c++  java
  • (函数)实现strstr函数

    • 题目:实现strstr函数。
    • 这个函数原型 strstr(char *a, char *b),在a中是否包含b这个字符串,包含返回第一个子串的位置,否则返回NULL。
    • 思路:其实这个就是找子串的问题。特殊情况,当b为空的时候,直接返回a;当b不为空的时候,指定start指针,通过两次循环,逐一对strstr中的子串和b进行匹配,如果b走到末尾,表示找到,start指针指向开始位置,否则start继续往前,

      例子:abcdefg    bcd  
              start指向a的位置,  将abcdefg和bcd比较   ->否
              start前进,指向b的位置,  将bcdefg和bcd比较  -> 是   返回start指针。

    • 代码
      class Solution {
      public:
          char *strStr(char *haystack, char *needle) {
              if (!*needle)
                  return haystack;
              char *start = haystack;
              char *temp1 = haystack, *temp2 = needle;
              while (*start){
                  temp1 = start;
                  temp2 = needle;
                  while (*temp2 && temp1 && !(*temp2 - *temp1))
                      temp2++, temp1++;
                  if (!*temp2)
                      return start;
                  start++;
              }
              return NULL;
          }
      };
  • 相关阅读:
    SpringBoot项目设置maven打包时间
    SpringBoot热部署配置
    Git笔记
    SpringBoot LogBack日志配置
    CURL使用教程
    Linux 安装Docker及使用
    转发和重定向的区别
    16周作业
    16
    15周
  • 原文地址:https://www.cnblogs.com/Kobe10/p/6366174.html
Copyright © 2011-2022 走看看