strStr

strstr (a.k.a find sub string), is a useful function in string operation. Your task is to implement this function.

For a given source string and a target string, you should output the firstindex(from 0) of target string in source string.

If target does not exist in source, just return -1.

Have you met this question in a real interview? 
Yes
Example

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

Challenge

O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)

Clarification

Do I need to implement KMP Algorithm in a real interview?

  • Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure your confirm with the interviewer first.

题目至少有3种方法,第一种是暴力搜索,每次移动一步,则时间复杂度为O(nm),其中n表示source的长度,m表示target的长度。第二种方法是在第一种方法的基础上做了改进,每次对比时,同时从两边向中间夹,这样可以适当降低时间复杂度;第三种方法,肯定就是KMP了,KMP算法优化的是第一二种方法存在的回溯问题,第一二种方法中,每次移动i到达某个值,使得source[i] != target[j]的时候,会回溯到i - j + 1的位置,也就是说[i-j+1, i]这个区间又要重复计算;

KMP算法的提出就是要避免此回溯,使得i只往后移,也就是说,这样的时间复杂度将是O(N),N为source的长度。KMP的算法证明,就不详细展开了;这里主要讲下next[j]的求解,其实在求解next[j]的过程有递归的含义在其中,也是在做一个字符串的匹配问题,有两个变量k,j,分别初始化为k = -1, j = 0,next[0] = -1;当k == -1 或者 target[k] == target[j]的时候,则说明next[j + 1] = k + 1; 否则的话,则将k移动到next[k],这一步就包括了递推的字符串匹配在其中,理解起来比较难;

class Solution {
public:
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    //KMP算法
    void GetNext(const char *p, vector<int> &next)
    {
        int len = strlen(p);
        int k = -1, j = 0;
        while(j < len - 1)
        {
            if(k == -1 || p[k] == p[j])
            {
                next[++j] = ++k;
            }
            else
                k = next[k];
        }
    }
    
    
    int strStr(const char *source, const char *target) {
        // write your code here
        if(source == NULL || target == NULL)
            return -1;
        int lens = strlen(source);
        int lent = strlen(target);
        if(lens < lent)
            return -1;
        int i = 0, j = 0;
        vector<int> next(lent, -1);
        GetNext(target, next);
        while(i < lens && j < lent)
        {
            if(j == -1)
            {
                ++i;
                j = 0;
            }
            else if(source[i] == target[j])
            {
                ++i;
                ++j;
            }
            else 
            {
                j = next[j];
            }
        }
        
        if(j >= lent)
            return i - j;
        return -1;
    }
};

 
<think>我们正在讨论`strstr`函数的使用方法。根据引用内容,`strstr`函数用于在字符串中查找子串,并返回第一次出现的位置的指针。如果未找到,则返回NULL。 关键点: 1. 函数原型:`char *strstr(const char *haystack, const char *needle);` 2. 参数说明: - haystack: 要被查找的字符串(主串) - needle: 要查找的子串 3. 返回值: - 找到:返回指向主串中第一次出现子串的位置的指针(即子串第一个字符在主串中的地址) - 未找到:返回NULL 我们将通过步骤详解来介绍使用方法,并给出示例代码。 </think>### `strstr`字符串查找函数详解 #### 一、核心功能与语法 `strstr()` 用于在主字符串中查找子字符串,函数原型为: ```c char *strstr(const char *haystack, const char *needle); ``` - **参数说明** - `haystack`:待搜索的主字符串(如 `"Hello world!"`) - `needle`:要查找的子字符串(如 `"world"`) - **返回值** - 找到子串:返回**首次出现位置的指针**(如指向主串中 `'w'` 的地址) - 未找到:返回 `NULL` ```c #include <stdio.h> #include <string.h> // 必须包含的头文件 int main() { char str1[] = "This is a simple string"; char *result = strstr(str1, "simple"); // 查找子串 printf("找到的位置: %s\n", result); // 输出: "simple string" } ``` [^1] --- #### 二、使用步骤与示例 ##### 1. 基础查找 ```c char email[] = "user@example.com"; char *domain = strstr(email, "@"); if (domain != NULL) { printf("域名: %s\n", domain + 1); // 输出: "example.com" } ``` ##### 2. 替换子串(结合 `strncpy`) ```c char text[] = "I like apples"; char *pos = strstr(text, "apples"); if (pos) { strncpy(pos, "oranges", 7); // 替换为等长的"oranges" printf("%s\n", text); // 输出: "I like oranges" } ``` [^4] ##### 3. 检测子串存在性 ```c char log[] = "Error: File not found"; if (strstr(log, "Error") != NULL) { printf("系统发生错误\n"); } ``` --- #### 三、模拟实现(BF算法) ```c char* my_strstr(const char* str1, const char* str2) { if (*str2 == '\0') return (char*)str1; // 空子串直接返回主串 const char *s1 = str1; while (*s1) { const char *p = s1; // 主串当前位置 const char *s2 = str2; // 子串起始位置 // 逐字符比较 while (*p && *s2 && *p == *s2) { p++; s2++; } if (*s2 == '\0') return (char*)s1; // 子串全部匹配 s1++; // 主串指针后移 } return NULL; // 未找到 } ``` [^5] --- #### 四、关键注意事项 1. **区分大小写**: `strstr("ABC", "abc")` 返回 `NULL`(大小写敏感) 2. **空子串处理**: 若 `needle` 为空字符串(`""`),返回 `haystack` 首地址 3. **重叠内存安全**: `strstr` 本身安全,但结合 `strncpy` 修改时需确保目标空间足够 4. **性能特性**: - 时间复杂度:最坏情况 $O(n \times m)$($n,m$ 为主串和子串长度) - 适合短文本搜索,长文本建议用 KMP 等高效算法 --- #### 五、典型错误案例 ```c char msg[20] = "Hello"; char *p = strstr(msg, "Hello"); strncpy(p, "Hi", 3); // 错误!"Hi"仅2字符,但复制3字节会覆盖后续内容 // 正确写法:strncpy(p, "Hi\0", 3); 或确保目标空间独立 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值