zoukankan      html  css  js  c++  java
  • LeetCode 28. Implement strStr()

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    两个字符串A和B, 在A中查找是否出现过B, 如果出现就返回第一次出现的下标, 如果没有就返回-1

    用暴力的方法求解,假设A字符串长度为N, B字符串长度为K, 则时间复杂度是N*K , LeetCode的评价是

     程序如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    class Solution {
    public:
        int strStr(string haystack, string needle) {
            int i=0;
            if(haystack.size()<needle.size())
                return -1;
            while(1)
            {
                //边界处理
                if(i>(haystack.size()-needle.size()))
                    break;
                int flag=0;//记录是否会遇到不一致的字符
                int k=0;//needle的下标
                for(int j=0;j<needle.size();j++)
                    if(needle[j]!=haystack[j+i]){
                        i++;
                        flag=1;
                        break;
                    }
                    else{
                        k++;
                    }
                if(flag==0){
                    return i;
                }
            }
            return -1;
        }
    };





  • 相关阅读:
    excel转换为dta格式
    移动pdf
    豆瓣爬虫
    python给证件照换底色
    OS模块
    决策树参数
    Pandas数据连接
    Sklearn用法
    numpy.loadtxt()用法
    单片机基础(五):定时/计数器的工作原理及工作方式
  • 原文地址:https://www.cnblogs.com/gremount/p/5774155.html
Copyright © 2011-2022 走看看