C++ leetcode实现strstr C++;返回指针
实现strStr() 返回指向第一个出现在haystack中的指针,如果指针不是haystack的一部分,则返回null 我写道:C++ leetcode实现strstr C++;返回指针,c++,C++,实现strStr() 返回指向第一个出现在haystack中的指针,如果指针不是haystack的一部分,则返回null 我写道: class Solution { public: char *strStr(char *haystack, char *needle) { std::string s1(haystack); std::string s2(needle); if(s2.empty()) {return haystack;} in
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;
}
};
类解决方案{
公众:
char*strStr(char*haystack,char*pinder){
std::字符串s1(干草堆);
标准:字符串s2(针);
if(s2.empty())
{返回干草堆;}
int a=s1.length();
int b=s2.length();
if(a
但是Leetcode给了我编译器错误:警告:从不同大小的整数转换为指针[-Wint到指针转换]
…我应该返回一些其他东西吗?…如果你把
字符串想象成一个字符序列,那么(char*)s1[I]
实际上是在代码段中投射字符->字符*
if(j == b)
{return (char*) s1[i];}
运算符[]
返回字符串的第i个字符。(,)
这有两个问题。首先,将字符的值转换为指针。您希望返回字符的地址,而不是转换为指针的值。其次,s1
是从haystack
参数初始化的本地std::string
。您不希望返回指向其中一个字符的指针,因为一旦函数返回,它将超出范围。您需要指向原始haystack
c字符串中的字符的指针
return &haystack[i];
可以使用std::string::find
简化。。看到您正在使用std::string
。。否则,请清除它并使用strlen
。
return &haystack[i];