Leetcode: 實現 strStr()

題目:

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回  -1。

示例 1:

輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:

輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf() 定義相符。

解法1:

class Solution {
    public int strStr(String haystack, String needle) {
        int result = -1;
        if ("".equals(needle)) {
            // 如果 needle 爲空字符串
            return 0;
        }

        // 每次去除 haystack 的第一字母后生成新的字符串
        // 判斷新的字符串是否是以 needle爲開始
        for (int i = 0; i <= haystack.length() - 1; i++) {
            boolean isStart= haystack.substring(i, haystack.length()).startsWith(needle);
            if (isStart) {
                result = i;
                break;
            }
        }
        return result;
    }
}

此種解法耗時有點長。

解法2:

class Solution {
    public int strStr(String haystack, String needle) {
        int result = -1;
        if ("".equals(needle)) {
            // 如果 needle 爲空字符串
            return 0;
        }
        // 當 needle 的長度比 haystack 長的情況
        if (needle.length() > haystack.length()) {
            return result;
        }
        // 判斷以 needle 在 字符串 haystack 的字符串位置
        int index = haystack.indexOf(needle);
        if (index >= 0) {
            result = index;
        }
        return result;
    }
}

解法3:

class Solution {
    public int strStr(String haystack, String needle) {
        int result = -1;
        if ("".equals(needle)) {
            // 如果 needle 爲空字符串
            return 0;
        }
        char[] h = haystack.toCharArray();
        char[] n = needle.toCharArray();
        if (n.length > h.length) {
            return -1;
        }
        for (int i = 0; i <= h.length - 1; i++) {
            if (result >= 0) { // 當遍歷完 needle 後,並且有正確的起點,則跳出 haystack 的循環
                break;
            }
            // 只有當 haystack 的字符與 needle 的起始字符一樣時候纔要必要去遍歷 needle
            // 並且設置 result 爲 i
            if (h[i] != n[0]) {
                continue;
            }
            result = i;
            for (int j = 1; j <= n.length - 1; j++) {
                if (j + result > h.length - 1) {    // 當 j + result 已經超出 haystack,則判斷比較失敗跳出循環,而且沒有繼續比較的意義了
                    return -1;
                }
                if (n[j] != h[j + result]) {    // needle 某個字符與 haystack不同,則跳出循環
                    result = -1;
                    break;
                }
            }
        }
        return result;
    }
}

前面兩種解法都調用了 Java原生的 API,沒有太大的意義,解法3的結果出乎意料。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章