mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加 1002.查找常用字符.md Scala版本
This commit is contained in:
@ -418,6 +418,38 @@ char ** commonChars(char ** words, int wordsSize, int* returnSize){
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Scala:
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def commonChars(words: Array[String]): List[String] = {
|
||||||
|
// 声明返回结果的不可变List集合,因为res要重新赋值,所以声明为var
|
||||||
|
var res = List[String]()
|
||||||
|
var hash = new Array[Int](26) // 统计字符出现的最小频率
|
||||||
|
// 统计第一个字符串中字符出现的次数
|
||||||
|
for (i <- 0 until words(0).length) {
|
||||||
|
hash(words(0)(i) - 'a') += 1
|
||||||
|
}
|
||||||
|
// 统计其他字符串出现的频率
|
||||||
|
for (i <- 1 until words.length) {
|
||||||
|
// 统计其他字符出现的频率
|
||||||
|
var hashOtherStr = new Array[Int](26)
|
||||||
|
for (j <- 0 until words(i).length) {
|
||||||
|
hashOtherStr(words(i)(j) - 'a') += 1
|
||||||
|
}
|
||||||
|
// 更新hash,取26个字母最小出现的频率
|
||||||
|
for (k <- 0 until 26) {
|
||||||
|
hash(k) = math.min(hash(k), hashOtherStr(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 根据hash的结果转换输出的形式
|
||||||
|
for (i <- 0 until 26) {
|
||||||
|
for (j <- 0 until hash(i)) {
|
||||||
|
res = res :+ (i + 'a').toChar.toString
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user