这道题,完全没什么印象,看着也有点懵逼。。。
先把代码粘过来,不看老代码,不收影响,从头想一个 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 month,I am totally another person!!
下面的代码是一遍过的,
几个关键位置的设置写得非常精准,
比如for中i的上限,比如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;
}
}