[leedcode 28] Implement strStr()
3626 ワード
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
public class Solution {
public int strStr(String haystack, String needle) {
// , haystack, needle 。 for
// flag
// , ,
if(needle.length()==0) return 0;
if(haystack.length()==0) return -1;
int lenH=haystack.length();
int lenN=needle.length();
boolean flag=true;
for(int i=0;i<=lenH-lenN;i++){
if(haystack.charAt(i)==needle.charAt(0)){
/* int temp=i+1;
for(int j=1;j<lenN;j++){
if(haystack.charAt(temp)!=needle.charAt(j)){
flag=false;
break;
}else{
temp++;
}
}*/
for(int j=0;j<lenN;j++){
if(haystack.charAt(j+i)!=needle.charAt(j)){
flag=false;
break;
}
}
////////////////
if(flag){
return i;
}
flag=true;//
}
}
return -1;
}
}