mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加1002.查找常用字符 Ruby实现
This commit is contained in:
@ -518,6 +518,54 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
Ruby:
|
||||
```ruby
|
||||
def common_chars(words)
|
||||
result = []
|
||||
#统计所有字符串里字符出现的最小频率
|
||||
hash = {}
|
||||
#初始化标识
|
||||
is_first = true
|
||||
|
||||
words.each do |word|
|
||||
#记录共同字符
|
||||
chars = []
|
||||
word.split('').each do |chr|
|
||||
#第一个字符串初始化
|
||||
if is_first
|
||||
chars << chr
|
||||
else
|
||||
#字母之前出现过的最小次数
|
||||
if hash[chr] != nil && hash[chr] > 0
|
||||
hash[chr] -= 1
|
||||
chars << chr
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
is_first = false
|
||||
#清除hash,更新字符最小频率
|
||||
hash.clear
|
||||
chars.each do |chr|
|
||||
if hash[chr] != nil
|
||||
hash[chr] += 1
|
||||
else
|
||||
hash[chr] = 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
#字符最小频率hash转换为字符数组
|
||||
hash.keys.each do |key|
|
||||
for i in 0..hash[key] - 1
|
||||
result << key
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user