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

    题目:Implement strStr().

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

    思路:从后向前

    最难得方法是使用KMP算法,不过程序是easy级别的,应该是可以使用从前往后的算法的。效率为n的平方。

    代码:

    class Solution {
    public:
        int strStr(string haystack, string needle) {
            
            if(needle.length()<1){
                return 0;
            }
            
            int length1=haystack.length();
            int length2=needle.length();
            int i,j;
            for(i=0;i<=length1-length2;i++){
                if(haystack[i]==needle[0]){
                    for(j=0;j<length2;j++){
                        if(haystack[i+j]!=needle[j]){
                            break;
                        }
                    }
                    if(j==length2){
                        
                        return i;
                    }
                }
            }
            return -1;
        }
    };


  • 相关阅读:
    设计模式-代理模式
    设计模式-策略模式
    设计模式-单例模式
    优先队列
    n!中质因子个数
    计算组合数
    高精度
    memset用法
    质因子分解
    素数筛法
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519895.html
Copyright © 2011-2022 走看看