leetcode实现strstr c++返回指针

leetcode implemente strstr C++ return pointers

本文关键字:返回 指针 c++ strstr 实现 leetcode      更新时间:2023-10-16

实现strStr().

返回一个指针,指向第一次出现在haystack中的needle,如果needle不是haystack的一部分,则返回null。

我写的

:

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
    std::string s1(haystack);
    std::string s2(needle);
    if(s2.empty())
      {return haystack;}
    int a = s1.length();
    int b = s2.length();
    if(a < b)
      {return NULL;}
    for(int i = 0; i < a - b; i++)
      {
          int j = 0;
          int k = i;
          while(j < b && s2[j] == s1[k])
            {
                k++;
                j++;
            }
          if(j == b)
            {return (char*) s1[i];}
      }
      else return NULL;
    }
};

但是Leetcode给了我编译错误:警告:从不同大小的整数转换为指针[-Wint-to-pointer-cast]

…我应该返回一些其他的东西吗?.....

return (char*) s1[i];

有两个问题。首先,将字符的值转换为指针。您希望返回字符的地址,而不是将其值转换为指针。其次,s1是从haystack参数初始化的本地std::string。您不希望返回指向其中一个字符的指针,因为一旦函数返回,它将超出作用域。您需要一个指向原始haystack c-string中的字符的指针。

return &haystack[i];

如果您将string想象为一个字符序列,那么(char*) s1[i]实际上是在代码段

中转换char -> char *
if(j == b)
    {return (char*) s1[i];}

operator[]返回字符串的第i个字符。(http://www.cplusplus.com/reference/string/string/, http://www.cplusplus.com/reference/string/string/operator[]/)