美文网首页
28-Implement strStr()

28-Implement strStr()

作者: cocalrush | 来源:发表于2017-04-13 00:14 被阅读0次

Implement strStr().

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

实现String的index函数

实现比较简单, 但是需要注意细节:

public class Solution {
    public int strStr(String haystack, String needle) {
        if(null == haystack || null == needle) return -1;
        if("".equals(needle)) return 0;
        int neLen = needle.length();
        int hayLen = haystack.length();
        for(int i=0;i<=hayLen - neLen; i ++){
            if(haystack.charAt(i) == needle.charAt(0)){
                int j = 1;
                for(;j<neLen;j++){
                    if(haystack.charAt(i + j) != needle.charAt(j)){
                        break;
                    }
                }
                if(j == neLen){
                    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;
    }
  }
}

相关文章

网友评论

      本文标题:28-Implement strStr()

      本文链接:https://www.haomeiwen.com/subject/jqvvattx.html