strStr


Question

Implement strStr().

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

Solution

屬於簡單的題目,基本上兩層 for 可以解決。可以記一下第二層的 for 要怎麼寫比較漂亮

public int strStr(String haystack, String needle) {
        if (needle.length() == 0 || haystack == null || needle == null) {
            return 0;
        }

        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            for (int j = 0; j < needle.length() && haystack.charAt(i+j) == needle.charAt(j); j++) {
                if (j == needle.length()-1) {
                    return i;
                }
            }
        }
        return -1;
    }

results matching ""

    No results matching ""