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算法(子串匹配的更高效算法)
     
  • 相关阅读:
    聚簇索引与非聚簇索引(二级索引)的区别
    swoole介绍
    什么是mysql执行计划
    php-fpm浅析
    字段设计规范
    mysql排序规则utf8_genera_ci和utf8_bin的区别
    chrome 麦克风被禁用
    获取地址栏参数
    vue 打包去掉console debugger
    Vue less全局变量预处理加载
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224836.html
Copyright © 2011-2022 走看看