规范格式

This commit is contained in:
YDZ
2020-08-07 15:50:06 +08:00
parent 854a339abc
commit 4e11f4028a
1438 changed files with 907 additions and 924 deletions

View File

@ -0,0 +1,33 @@
package leetcode
import "math"
func commonChars(A []string) []string {
cnt := [26]int{}
for i := range cnt {
cnt[i] = math.MaxUint16
}
cntInWord := [26]int{}
for _, word := range A {
for _, char := range []byte(word) { // compiler trick - here we will not allocate new memory
cntInWord[char-'a']++
}
for i := 0; i < 26; i++ {
// 缩小频次,使得统计的公共频次更加准确
if cntInWord[i] < cnt[i] {
cnt[i] = cntInWord[i]
}
}
// 重置状态
for i := range cntInWord {
cntInWord[i] = 0
}
}
result := make([]string, 0)
for i := 0; i < 26; i++ {
for j := 0; j < cnt[i]; j++ {
result = append(result, string(rune(i+'a')))
}
}
return result
}

View File

@ -0,0 +1,47 @@
package leetcode
import (
"fmt"
"testing"
)
type question1002 struct {
para1002
ans1002
}
// para 是参数
// one 代表第一个参数
type para1002 struct {
one []string
}
// ans 是答案
// one 代表第一个答案
type ans1002 struct {
one []string
}
func Test_Problem1002(t *testing.T) {
qs := []question1002{
question1002{
para1002{[]string{"bella", "label", "roller"}},
ans1002{[]string{"e", "l", "l"}},
},
question1002{
para1002{[]string{"cool", "lock", "cook"}},
ans1002{[]string{"c", "o"}},
},
}
fmt.Printf("------------------------Leetcode Problem 1002------------------------\n")
for _, q := range qs {
_, p := q.ans1002, q.para1002
fmt.Printf("【input】:%v 【output】:%v\n", p, commonChars(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,33 @@
# [1002. Find Common Characters](https://leetcode.com/problems/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.
You may return the answer in any order.
**Example 1:**
Input: ["bella","label","roller"]
Output: ["e","l","l"]
**Example 2:**
Input: ["cool","lock","cook"]
Output: ["c","o"]
**Note:**
1. `1 <= A.length <= 100`
2. `1 <= A[i].length <= 100`
3. `A[i][j]` is a lowercase letter
## 题目大意
给定仅有小写字母组成的字符串数组 A返回列表中的每个字符串中都显示的全部字符包括重复字符组成的列表。例如如果一个字符在每个字符串中出现 3 次,但不是 4 次,则需要在最终答案中包含该字符 3 次。你可以按任意顺序返回答案。
## 解题思路
- 简单题。给出一个字符串数组 A要求找出这个数组中每个字符串都包含字符如果字符出现多次在最终结果中也需要出现多次。这一题可以用 map 来统计每个字符串的频次,但是如果用数组统计会更快。题目中说了只有小写字母,那么用 2 个 26 位长度的数组就可以统计出来了。遍历字符串数组的过程中,不过的缩小每个字符在每个字符串中出现的频次(因为需要找所有字符串公共的字符,公共的频次肯定就是最小的频次),得到了最终公共字符的频次数组以后,按顺序输出就可以了。