28-subStr() 以及size_t注意事项

size_t

size_t是 unsigned integer type,即一种非负的整数类型,使用时需要注意,下面的代码会导致错误:

string str1="aa";
string str2="aaaa";
if(str1.size()-str2.size()<0)
{
     ...  
}

上面的代码中,会将  str1.size()-str2.size()  结果存储在一个size_t类型中,如果结果为负,则会是一个很大的正值,与预期不符,可使用auto验证:

auto val = str1.size()-str2.size();  

在对size()等函数的返回值做数值运算时,最好先将各个size()返回值赋值给int然后再运算,避免不必要的错误。

 https://zh.cppreference.com/w/cpp/types/size_t

substr

<string>中的函数,用于根据起始位置、长度,获取子字符串,定义如下,注意第二个参数为子字符串长度,而不是第二个索引!

题目28

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2


示例 2:

输入: haystack = "aaaaa", needle = "bba"

输出: -1
说明:

  当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

  对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

解答:

自己的代码:

int strStr(string haystack, string needle) 
{
    if (needle.size() == 0)
        return 0;
    if (haystack.size() == 0)
        return -1;

    for (int i = 0; i < haystack.size(); i++)
    {
        if (haystack[i] != needle[0])
            continue;

        //找到第一个相等的字符后,判断长度够不够
        if (i + needle.size()-1 >= haystack.size())
            return -1;

        if (haystack.substr(i, needle.size()) == needle)
            return i;
    }

    return -1;
}

上面的代码可以优化,即每次都判断长度是否够,可以修改为如下代码:

int strStr2(string haystack, string needle)
{
    if (needle.size() == 0)
        return 0;
    if (haystack.size() == 0)
        return -1;
    
    //size_t 是unsigned类型数据,拿小的size-大的size会得到一个很大的值!!!
    //int val = haystack.size() - needle.size();
    //auto val2 = haystack.size() - needle.size();
    //if (haystack.size() - needle.size() < 0)
    /*if (haystack.size() < needle.size())
        return -1;*/

    int len1 = haystack.size();
    int len2 = needle.size();
    for (int i = 0; i < len1 - len2; i++)
    {
        if (haystack[i] != needle[0])
            continue;
        if (haystack.substr(i, len2) == needle)
            return i;
    }

    return -1;

题解:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode/

原文地址:https://www.cnblogs.com/zyk1113/p/14005498.html