zoukankan      html  css  js  c++  java
  • 【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算法(子串匹配的更高效算法)
     
  • 相关阅读:
    angular9的学习(十)
    本周学习总结
    本周学习总结
    angular9的学习(九)
    本周学习总结
    Web地图呈现原理
    小程序Canvas性能优化实战
    地图SDK全新版本v4.3.0上线
    硬核干货来了!手把手教你实现热力图!
    地图SDK全面升级 – 数十项新功能及优化等你来体验
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224836.html
Copyright © 2011-2022 走看看