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.

    Subscribe to see which companies asked this question

    实现判断一个字符串是否是一个字符串的子串。如果是,返回该子串第一次出现的位置,如果不是返回-1;

    这道题一下子让我想到KMP算法,于是去学习了一下KMP算法。(详见文章1

    但是KMP实现好复杂,尤其是那个部分匹配表,所以,还是自己想了。

    后来就想到这个方法。

    组成每个小子串,然后盘点是否匹配。

    class Solution {
    public:
        bool isSame(string s,string t){
            if(s==t) return true;
            else return false;
        }
        int strStr(string haystack, string needle) {
            int len1=haystack.length();
            int len2=needle.length();
            string tmp="";
            if(len2>len1) return -1;
            if(len2==len1) {
                if(isSame(haystack,needle)) return 0;
                else return -1;
            }
            for(int i=0;i<=len1-len2;i++){
                tmp="";
                for(int j=i;j<i+len2;j++) tmp+=haystack[j];
                if(isSame(tmp,needle)) return i;
            }
            return -1;
        }
    };
  • 相关阅读:
    弹性盒子
    bzoj4237 稻草人
    bzoj2654 tree
    bzoj4813 [Cqoi2017]小Q的棋盘
    bzoj1014 [JSOI2008]火星人
    bzoj3242 [Noi2013]快餐店
    bzoj4025 二分图
    bzoj3237 [Ahoi2013]连通图
    bzoj3244 [Noi2013]树的计数
    bzoj2431 [HAOI2009]逆序对数列
  • 原文地址:https://www.cnblogs.com/LUO77/p/5072909.html
Copyright © 2011-2022 走看看