Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6be5368

Browse files
Merge pull request youngyangyang04#2442 from CatNum/master
Update 1002.查找常用字符.md 更新Go版本-更新为与C++相同逻辑
2 parents 5a94778 + 13edf8d commit 6be5368

File tree

1 file changed

+38
-30
lines changed

1 file changed

+38
-30
lines changed

‎problems/1002.查找常用字符.md‎

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -327,37 +327,45 @@ var commonChars = function(words) {
327327
### GO
328328

329329
```golang
330-
func commonChars(words []string) []string {
331-
length:=len(words)
332-
fre:=make([][]int,0)//统计每个字符串的词频
333-
res:=make([]string,0)
334-
//统计词频
335-
for i:=0;i<length;i++{
336-
var row [26]int//存放该字符串的词频
337-
for j:=0;j<len(words[i]);j++{
338-
row[words[i][j]-97]++
339-
}
340-
fre=append(fre,row[:])
341-
}
342-
//查找一列的最小值
343-
for j:=0;j<len(fre[0]);j++{
344-
pre:=fre[0][j]
345-
for i:=0;i<len(fre);i++{
346-
pre=min(pre,fre[i][j])
347-
}
348-
//将该字符添加到结果集(按照次数)
349-
tmpString:=string(j+97)
350-
for i:=0;i<pre;i++{
351-
res=append(res,tmpString)
352-
}
353-
}
354-
return res
330+
func commonChars(A []string) []string {
331+
var result []string
332+
if len(A) == 0 {
333+
return result
334+
}
335+
336+
hash := make([]int, 26) // 用来统计所有字符串里字符出现的最小频率
337+
for _, c := range A[0] { // 用第一个字符串给hash初始化
338+
hash[c-'a']++
339+
}
340+
341+
for i := 1; i < len(A); i++ {
342+
hashOtherStr := make([]int, 26) // 统计除第一个字符串外字符的出现频率
343+
for _, c := range A[i] {
344+
hashOtherStr[c-'a']++
345+
}
346+
// 更新hash,保证hash里统计26个字符在所有字符串里出现的最小次数
347+
for k := 0; k < 26; k++ {
348+
hash[k] = min(hash[k], hashOtherStr[k])
349+
}
350+
}
351+
352+
// 将hash统计的字符次数,转成输出形式
353+
for i := 0; i < 26; i++ {
354+
for hash[i] > 0 {
355+
s := string('a' + i) // rune -> string
356+
result = append(result, s)
357+
hash[i]--
358+
}
359+
}
360+
361+
return result
355362
}
356-
func min(a,b int)int{
357-
if a>b{
358-
return b
359-
}
360-
return a
363+
364+
func min(a, b int) int {
365+
if a < b {
366+
return a
367+
}
368+
return b
361369
}
362370
```
363371

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /