LeetCode刷题之Implement strStr()

Problem

Implement strStr().

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

My Solution

class Solution {
    public int strStr(String haystack, String needle) {
                int i, j;
        if (haystack.length() < needle.length()) {
            return -1;
        } else if (haystack.equals("") && needle.equals("")) {
            return 0;
        }
        for (i = 0; i < haystack.length(); ++i) {
            for (j = 0; j < needle.length(); ++j) {
                if (haystack.length() - i < needle.length() - j) {
                    return -1;
                }
                if (haystack.charAt(i) != needle.charAt(j)) {
                    i = i - j;
                    j = 0;
                    break;
                }
                ++i;
            }
            if (j == needle.length()) {
                return i - j;
            }
        }
        return -1;
    }
}
Great Solution

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;
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,483评论 0 10
  • 最有效房地产销售的方法第一招:将最重要的卖点放在最前面说 根据首因效应这个销售心理学的理论,最先和客户介绍的卖点将...
    咏不放弃阅读 522评论 0 0
  • 今晚,我碰到以前的小学同学子成,他跟我提及起房子的事来,这点正是我感兴趣的,所以我投其所好抛出了个问题。 我也未能...
    第一次好紧张耶阅读 268评论 0 0
  • 小A说在她所有的关系中,妥协是底色: 和合作伙伴意见不同时:“她会对自己说和气生财,伤了关心就不值得了;” 与小伙...
    娟记阅读 641评论 0 10
  • 记百日共修毕业及新一轮共修的开学典礼 2018.12.17 昨天第一次到止定公司参加集体活动,一点没有陌生感,因为...
    蓝色梦幻_8ed1阅读 640评论 2 8