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;
    }
  }
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,872評論 0 10
  • 最有效房地產(chǎn)銷售的方法第一招:將最重要的賣點放在最前面說 根據(jù)首因效應這個銷售心理學的理論,最先和客戶介紹的賣點將...
    詠不放棄閱讀 544評論 0 0
  • 今晚,我碰到以前的小學同學子成,他跟我提及起房子的事來,這點正是我感興趣的,所以我投其所好拋出了個問題。 我也未能...
    第一次好緊張耶閱讀 291評論 0 0
  • 小A說在她所有的關系中,妥協(xié)是底色: 和合作伙伴意見不同時:“她會對自己說和氣生財,傷了關心就不值得了;” 與小伙...
    娟記閱讀 669評論 0 10
  • 記百日共修畢業(yè)及新一輪共修的開學典禮 2018.12.17 昨天第一次到止定公司參加集體活動,一點沒有陌生感,因為...
    藍色夢幻_8ed1閱讀 706評論 2 8

友情鏈接更多精彩內(nèi)容