Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1002. 查找常用字符 #62

Open
yankewei opened this issue Oct 14, 2020 · 1 comment
Open

1002. 查找常用字符 #62

yankewei opened this issue Oct 14, 2020 · 1 comment
Labels
哈希表 题目包含哈希表解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给定仅有小写字母组成的字符串数组 A,返回列表中的每个字符串中都显示的全部字符(包括重复字符)组成的列表。例如,如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。

你可以按任意顺序返回答案。

示例 1:

输入:["bella","label","roller"]
输出:["e","l","l"]

示例 2:

输入:["cool","lock","cook"]
输出:["c","o"]

提示:

  • 1 <= A.length <= 100
  • 1 <= A[i].length <= 100
  • A[i][j] 是小写字母

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-common-characters

@yankewei yankewei added 简单 题目难度为简单 哈希表 题目包含哈希表解法 labels Oct 14, 2020
@yankewei
Copy link
Owner Author

简单来说,就是把每个字符串中都包含的字符查出来就可以了,很容易的想到哈希表来做。因为都是小写英文字母,所以可以使用一个26位的数组,来表示每个字符串的每个字符的数量。

func commonChars(A []string) []string {
    var ret []string
    var slice [][26]int
    for _, v := range A {
	arr := [26]int{}
	for _, vv := range v {
	    arr[vv-'a']++
	}
	slice = append(slice, arr)
    }

    for i := 0; i < 26; i++ {
	minCnt := 127
	for _, v := range slice {
	    if v[i] < minCnt {
		minCnt = v[i]
	    }
	}
	if minCnt == 0 {
	    continue
	}
	str := string(i + 97)
	for j := minCnt; j > 0; j-- {
	    ret = append(ret, str)
	}
    }
    return ret
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant