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

        /*
         * 28. Implement strStr(); 
         * 2016-4-16 by Mingyang 
         * 非常简单的思路,刚开始自己写的杂乱无章,后面借鉴了网上简洁的代码
         * 利用substring来表达一个截取string的过程,非常有效,
         * 所以要学会借鉴substring等自带函数
         */
         public int strStr1(String haystack, String needle) {
                int len1=haystack.length();
                int len2=needle.length();
                if(len1==0){
                    return len2==0?0:-1;
                }
                if(len2==0)
                    return 0;
                if(len1<len2){
                    return -1;
                }
                //这里的len1-len2需要找好
                for(int i=0;i<=(len1-len2);i++){
                    int j=0;
                    int k=i;
                    while(j<len2&&k<len1){
                        if(haystack.charAt(k)==needle.charAt(j)){
                         k++;
                         j++;
                        }else{
                            break;
                        }
                    }
                    if(j==len2){
                        return i;//这里容易少一个
                    }
                }
                return -1;
            }
        public int strStr(String haystack, String needle) {
            int l1 = haystack.length(), l2 = needle.length();
            if (l1 < l2) {
                return -1;
            } else if (l2 == 0) {
                return 0;
            }
            int threshold = l1 - l2;
            for (int i = 0; i <= threshold; ++i) {
                if (haystack.substring(i, i + l2).equals(needle)) {
                    return i;
                }
            }
            return -1;
        }
  • 相关阅读:
    pyhanlp 实体命名识别
    NABCD需求分析
    源代码
    遇到的问题和解决方法
    运行及总结
    测试与调试
    读《一个程序猿的生命周期》和《人,绩效和职业道德》有感
    面向对象程序设计
    设计类图
    SRS文档
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5400243.html
Copyright © 2011-2022 走看看