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;
    }
  }
}
    原文作者:Gandalf0
    原文地址: https://www.jianshu.com/p/19ea7bf82fb8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞