题目

返回字符串haystack中第一次出现子字符串needle的index

Implement strStr().

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

https://leetcode.com/problems...


暴力算法

尝试

    public int strStr(String haystack, String needle) {
        char[] hay=haystack.toCharArray();
        char[] nee=needle.toCharArray();
        boolean flag=true;
        
        for(int i=0;i<hay.length-nee.length+1;i++,flag=true){
            for(int j=0;j<nee.length;j++){
                if(hay[i+j]!=nee[j]){
                    flag=false;
                    break;
                }
            }
            if(flag) return i;
        }
        
        return -1;
    }

借鉴

public int strStr(String haystack, String needle) {
  for (int i = 0; ; i++) {
    for (int j = 0; ; j++) {
      if (j == needle.length()) return i;
      if (i + j == haystack.length()) return -1;
      if (needle.charAt(j) != haystack.charAt(i + j)) break;
    }
  }
}
public int strStr(String haystack, String needle) {
  for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
    for (int j = 0; ; j++) {
      if (j == needle.length()) return i; //走到了最后,省去了boolean flag
      if (needle.charAt(j) != haystack.charAt(i + j)) break; //如果不同,则拉走下一个
    }
  }
  return -1;
}

KMP

http://www.cnblogs.com/reboot...


lindsay_bubble
26 声望11 粉丝

引用和评论

0 条评论