【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)
}

原文地址:https://blog.51cto.com/fulin0532/2432317

时间: 2024-08-29 22:53:59

【Golang语言】LeetCode 1002. Find Common Characters的相关文章

Leetcode 1002. Find Common Characters

python可重集合操作 class Solution(object): def commonChars(self, A): """ :type A: List[str] :rtype: List[str] """ if not A: return [] from collections import Counter ans=Counter(A[0]) for str in A: ans&=Counter(str) ans=list(an

1002. Find Common Characters - Easy

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

[LC] 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

golang的leetcode之路

对于leetcode,我有一种不知名的情绪.在我看来,Leetcode是一个对于算法正确性的在线评测系统OJ,作为ACMER,大家都明白这两个字母的含义.作为一个曾经的ACMER,在学校时接触的是各类算法和数据结构,也曾经奋斗过,也曾经失落过,也曾经辉煌过,也曾经低沉过.不管怎么样,我和算法和OJ结下了不解之缘. 为此在这新的开始来临时,我决定用golang在leetcode上进行一番书写,我将再次在这里记录我的足迹,我的奋斗,我的汗水以及我已经逝去的青春.这里先对golang打个广告,这门语言

用golang刷LeetCode

用golang刷LeetCode 用Go语言刷LeetCode记录,只是为了练习Go语言,能力有限不保证都是最优解,只能在此抛转引玉了. 数据结构和算法 数据结构和算法是程序员的命根子,没了命根子也就没有了尊严. 1. 两数之和 题目描述 力扣(LeetCode)链接 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素. 示例: 给定 nums

LeetCode 014 Longest Common Prefix

[题目] Write a function to find the longest common prefix string amongst an array of strings. [题意] 求一组字符串的最长公共前缀 [思路] 使用归并思想求解 要求字符串[1,2,..,k,k+1,...n]的最大公共前缀,先分别求[1,2,...k]和[k+1,...,n]的公共前缀 [代码] class Solution { public: string commonPrefix(vector<stri

学习Golang语言(6):类型--切片

学习Golang语言(1): Hello World 学习Golang语言(2): 变量 学习Golang语言(3):类型--布尔型和数值类型 学习Golang语言(4):类型--字符串 学习Golang语言(5):类型--数组 学习Golang语言(6):类型--切片 在很多应用场景中,数组不能够满足我们的需求.在初始定义数组时,我们并不知道数组所需的长度.因此,我们需要一个大小可以动态变化的数组(动态数组) 在Go语言中,这种"动态数组"成为slice(切片). 但是实际上slic

*Common characters

Write a program that gives count of common characters presented in an array of strings..(or array of character arrays) For eg.. for the following input strings.. aghkafgklt dfghako qwemnaarkf The output should be 3. because the characters a, f and k

[LeetCode] 158. Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. By using the read4 API, implement the function