Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

思路:

注意,在for循环中条件有计算得到的负数时, 一定要把计算括起来转换为int, 否则会默认转换为uchar 负数就会被误认为是一个很大的数字。

for(int i = 0; i < int(1 - 2); ++i)

 

实现很常规:

int strStr(string haystack, string needle) {
        for(int i = 0; i <= int(haystack.size() - needle.size()); ++i)
        {
            int j;
            for(j = 0; j < needle.size() && haystack[i + j] == needle[j]; ++j);
            if(j == needle.size())
                return i;
        }
        return -1;
    }

 

相关文章:

  • 2021-07-18
  • 2021-06-28
  • 2022-01-15
  • 2021-08-21
  • 2022-02-10
  • 2022-01-23
猜你喜欢
  • 2021-06-29
  • 2022-01-22
  • 2021-06-10
  • 2021-08-06
  • 2021-12-16
  • 2021-12-05
相关资源
相似解决方案