• 【LeetCode & 剑指offer刷题】字符串题8:Implement strStr()


    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Implement strStr()

     
    Implement strStr().
    Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
    Example 1:
    Input: haystack = "hello", needle = "ll"
    Output: 2
    Example 2:
    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    Clarification:
    What should we return when needle is an empty string? This is a great question to ask during an interview.
    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
     
    //问题:实现strstr函数,子串查找(子串匹配)
    //方法一:扫描主串,再扫描子串,O(mn)
    #include <string>
    class Solution
    {
    public:
        int strStr(string haystack, string needle)
        {
            int m = haystack.size(), n = needle.size();
            if(n == 0) return 0; //如果needle为空
           
         /*   int result = haystack.find(needle);
            if(result != string::npos) return result;
            else return -1;*/
               
            for(int i = 0; i <= m-n; i++) //扫描主串,最后一个位置起始索引为m-n, i = 0~m-n
            {
                int j =0;
                for(; j<n; j++) //扫描子串,j=0~n-1
                {
                    if(haystack[i+j] != needle[j]) break; //如果有某个字符不匹配则退出循环
                }
                if(j == n) return i; //如果均匹配,返回子串在主串中的起始索引
            }
            return -1; //如果未找到,则返回-1
           
        }
    };
    //方法二:KMP算法(子串匹配的更高效算法)
     
  • 相关阅读:
    Mac挂载分区
    连接SFTP命令
    【转】10.13.6蓝牙失效的解决方法(Broadcom-BCM94352z-DW1560)
    Jetbrains2020系列配置路径变动(Pycharm2020双击无法打开)
    libtorch 常用api函数示例(史上最全、最详细)
    有用链接
    cuda 编程1
    CMakeLists.txt
    模型压缩--剪枝,tensorrt实验调研
    iou map TP TN FP FN Precision Recall
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224836.html
Copyright © 2020-2023  润新知