Update 1002.查找常用字符.md 更新Go版本-更新为与C++相同逻辑

This commit is contained in:
anini
2024-02-17 12:42:10 +08:00
parent 5a94778ac8
commit e8e2f24963
2 changed files with 46 additions and 30 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -327,37 +327,45 @@ var commonChars = function(words) {
### GO ### GO
```golang ```golang
func commonChars(words []string) []string { func commonChars(A []string) []string {
length:=len(words) var result []string
fre:=make([][]int,0)//统计每个字符串的词频 if len(A) == 0 {
res:=make([]string,0) return result
//统计词频 }
for i:=0;i<length;i++{
var row [26]int//存放该字符串的词频 hash := make([]int, 26) // 用来统计所有字符串里字符出现的最小频率
for j:=0;j<len(words[i]);j++{ for _, c := range A[0] { // 用第一个字符串给hash初始化
row[words[i][j]-97]++ hash[c-'a']++
} }
fre=append(fre,row[:])
} for i := 1; i < len(A); i++ {
//查找一列的最小值 hashOtherStr := make([]int, 26) // 统计除第一个字符串外字符的出现频率
for j:=0;j<len(fre[0]);j++{ for _, c := range A[i] {
pre:=fre[0][j] hashOtherStr[c-'a']++
for i:=0;i<len(fre);i++{ }
pre=min(pre,fre[i][j]) // 更新hash保证hash里统计26个字符在所有字符串里出现的最小次数
} for k := 0; k < 26; k++ {
//将该字符添加到结果集(按照次数) hash[k] = min(hash[k], hashOtherStr[k])
tmpString:=string(j+97) }
for i:=0;i<pre;i++{ }
res=append(res,tmpString)
} // 将hash统计的字符次数转成输出形式
} for i := 0; i < 26; i++ {
return res for hash[i] > 0 {
s := string('a' + i) // rune -> string
result = append(result, s)
hash[i]--
}
}
return result
} }
func min(a,b int)int{
if a>b{ func min(a, b int) int {
return b if a < b {
} return a
return a }
return b
} }
``` ```