【Golang語言】LeetCode 1002. Find Common Characters

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

給定僅有小寫字母組成的字符串數組 A,返回列表中的每個字符串中都顯示的全部字符(包括重複字符)組成的列表。例如,如果一個字符在每個字符串中出現 3 次,但不是 4 次,則需要在最終答案中包含該字符 3 次。
你可以按任意順序返回答案。
https://leetcode-cn.com/problems/find-common-characters

Input: ["bella","label","roller"]
Output: ["e","l","l"]
Input: ["cool","lock","cook"]
Output: ["c","o"]

題意:找出所有字符串中都出現過的字符,其實就是求各個字符串的交集,可以按任意順序返回。
思路一:求每次字符串中的字符出現次數,每次兩兩字符串比較,26個字符取最小次數的則爲兩字符串的交集,比如
bella b->1 e->1 l->2 a->1
label b->1 e->1 l->2 a->1 所以這倆字符串的交集就是a b e l l
然後繼續往下遍歷即可。
用value-'a' 表示26個字母 最後再 value+'a' 轉回來


func commonChars(A []string) []string {
    result := make([]int, 26)
    for _, value := range A[0] {
        result[value-'a']++
    }
    for i := 1; i < len(A); i++ {
        temp := make([]rune, 26)
        for _, value := range A[i] {
            temp[value-'a']++
        }
        for j := 0; j < 26; j++ {
            result[j] = int(math.Min(float64(temp[j]), float64(result[j])))
        }
    }

    ret := make([]string, 0)
    for i := 0; i < 26; i++ {
        if result[i] > 0 {
            times := result[i]
            j := 0
            for j < times {
                ret = append(ret, string(i+'a'))
                j++
            }
        }
    }

    return ret
}

思路二:其實也是差不多,也是直接兩兩比較,求交集,比較到最後的結果就是最後的結果。不過這裏的求交集方法不太一樣。 由於要考慮到重複出現的字符,所以需要採用一個數組來記錄某個字符最近一次被找到的位置。如果再次遇到該字符,那麼將會從該位置後面開始尋找。

func commonChars1002(A []string) []string {
    result := make([]string, 0)
    if len(A) == 1 {
        for _, rune := range A[0] {
            result = append(result, string(rune))
        }

        return result
    }
    common := commonStr(A[0], A[1])
    for i := 2; i < len(A); i++ {
        common = commonStr(A[i], common)
    }
    for _, rune := range common {
        result = append(result, string(rune))
    }
    return result
}
func commonStr(a string, b string) string {
    indexMap := [26]int{}
    result := make([]rune, 0)
    index := 0
    for _, rune := range a {
        beforeIndex := indexMap[rune-'a']
        index = strings.Index(b[beforeIndex:], string(rune))
        if index < len(b) && index >= 0 {
            result = append(result, rune)
            indexMap[rune-'a'] = index + beforeIndex + 1//截取後索引會從0開始,所以得加上之前的
        }
    }
    return string(result)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章