• [leetcode 27]Implement strStr()


    1 题目:

    Implement strStr().

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

    Update (2014-11-02):
    The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

    2 思路:

    估计是要实现KMP算法。

    正好我从大二就开始想把它看懂。。。

    这次搞明白了。

    我是 谷歌 “KMP 通俗”,前面有三个帖子,看完后,差不多才懂得。

    3 代码:

        /* KMP method */
        // 
        public int strStr(String haystack, String needle) {
            // pre handle
            if( needle.length()==0){
                return 0;
            }
            if(haystack.length()==0){
                return -1;
            }
            
            char[] target = haystack.toCharArray();
            char[] point = needle.toCharArray();
        
            // build the point array, the last feature[len-1] not satify the sub-prifix & sub-suffix rule, but not matter,the feature[len-1] will not be use
            Integer[] feature = new Integer[needle.length()];
            feature[0] = 0;
            for(int i=1; i<needle.length()-1; i++){
                if(point[i]!=point[feature[i-1]]){
                    feature[i] = 0;
                }else{
                    feature[i] = feature[i-1]+1;
                }
            }
            
            // search
            int j = 0;
            for(int i=0; i<haystack.length();){
                if(target[i]==point[j]){
                    j++;
                    if(j == needle.length()){
                        // match, return index
                        return i-j+1;
                    }
                    i++;
                }else{
                    if(j == 0){
                        /* j=0 not match,i++ */
                        i++;
                    }else{
                        /* not match, continue to compare target[i] */
                        j = feature[j-1];
                    }
                }
            }
            
            return -1;
        }
  • 相关阅读:
    使用url_for()时,会自动调用转换器的to_url()方法
    自定义flask转换器
    flask自有转换器:int、float、path。默认string
    flask中重定向所涉及的反推:由视图函数反推url
    mysqldump 命令使用
    PIX 防火墙
    MySQL 常用show 语句
    防火墙与入侵检测技术
    mysql DQL语言操作
    mysql 视图
  • 原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4827340.html
Copyright © 2020-2023  润新知