28 Implement strStr()

这道题,完全没什么印象,看着也有点懵逼。。。

先把代码粘过来,不看老代码,不收影响,从头想一个 de nove 的算法。。。

public class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack.length()<needle.length()) return -1;
        else if(haystack.length()==0 && needle.length()==0) return 0; // both empty, return 0;
        // important!!! 1, haystack should be >= need; 2, but if both them are empty, should return 0
        
        else{
            int len1=haystack.length(), len2=needle.length();
            int i=0;
            while(i<=len1-len2){   // i<=len1-len2; not i=< len1-len2 !!!!
                int j;
                for(j=0; j<len2; j++){
                    if(haystack.charAt(i+j)!=needle.charAt(j)) break; // !!! damn, I wrote haystack[i+j]!=needle[j], PLS, pay attension to String vs array, although they are essentially array problem, but the way to access element is different.     
                }
                if(j==len2)  return i;  // if j go through every index, it mean all char matched, since++ out of for loop, j==len2, 
                //!!! damn, if you want to catch j after the for loop, need to initialize it before the loop, so its not a local variable;
                //### typic mistake;
                i++; // in while loop, remember to change the condition!!!!
            }
            // if not returned after all loop, there is somehow mismatch in between.
            return -1;
        }
    }
}

/**
 done in 8 mins, similar to rm dup and rm target, there single char is compared, here the target is a substring, so use a for loop.
 essentially the same property, which is the logic and the code frame work. Suttle differenc below
 Question      difference:
 rm dup_ch:    changing char
 rm tar_ch:    constant char
 chk sub_str:   constant substring

*/

思路确实清晰多了

代码也比较精炼成熟。。。

也就是2周的时间练习,像这样高强度的锻炼,确实可以达到:after one monthI am totally another person!!

下面的代码是一遍过的,

几个关键位置的设置写得非常精准,

比如fori的上限比如if中的判断,substring中的第二个参数

代码风格确实成熟多了。。


今天的代码:

public class Solution {
    public int strStr(String haystack, String needle) {
        int len1=needle.length();
        int len2=haystack.length();
        for(int i=0; i<len2-(len1-1); i++){
            if(i+len1-1<len2 && needle.equals(haystack.substring(i,i+len1))) return i;
        }
        return -1;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值