28-Implement strStr()

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;
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容