Skip to content

Commit 74b76bf

Browse files
committed
添加 1002.查找常用字符.md Scala版本
1 parent cf4c25b commit 74b76bf

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,38 @@ char ** commonChars(char ** words, int wordsSize, int* returnSize){
418418
return ret;
419419
}
420420
```
421-
421+
Scala:
422+
```scala
423+
object Solution {
424+
def commonChars(words: Array[String]): List[String] = {
425+
// 声明返回结果的不可变List集合,因为res要重新赋值,所以声明为var
426+
var res = List[String]()
427+
var hash = new Array[Int](26) // 统计字符出现的最小频率
428+
// 统计第一个字符串中字符出现的次数
429+
for (i <- 0 until words(0).length) {
430+
hash(words(0)(i) - 'a') += 1
431+
}
432+
// 统计其他字符串出现的频率
433+
for (i <- 1 until words.length) {
434+
// 统计其他字符出现的频率
435+
var hashOtherStr = new Array[Int](26)
436+
for (j <- 0 until words(i).length) {
437+
hashOtherStr(words(i)(j) - 'a') += 1
438+
}
439+
// 更新hash,取26个字母最小出现的频率
440+
for (k <- 0 until 26) {
441+
hash(k) = math.min(hash(k), hashOtherStr(k))
442+
}
443+
}
444+
// 根据hash的结果转换输出的形式
445+
for (i <- 0 until 26) {
446+
for (j <- 0 until hash(i)) {
447+
res = res :+ (i + 'a').toChar.toString
448+
}
449+
}
450+
res
451+
}
452+
}
453+
```
422454
-----------------------
423455
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
 (0)