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 3933b49

Browse files
添加1002.查找常用字符 Ruby实现
1 parent 1340cc3 commit 3933b49

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,54 @@ impl Solution {
518518
}
519519
```
520520

521+
Ruby:
522+
```ruby
523+
def common_chars(words)
524+
result = []
525+
#统计所有字符串里字符出现的最小频率
526+
hash = {}
527+
#初始化标识
528+
is_first = true
529+
530+
words.each do |word|
531+
#记录共同字符
532+
chars = []
533+
word.split('').each do |chr|
534+
#第一个字符串初始化
535+
if is_first
536+
chars << chr
537+
else
538+
#字母之前出现过的最小次数
539+
if hash[chr] != nil && hash[chr] > 0
540+
hash[chr] -= 1
541+
chars << chr
542+
end
543+
end
544+
end
545+
546+
is_first = false
547+
#清除hash,更新字符最小频率
548+
hash.clear
549+
chars.each do |chr|
550+
if hash[chr] != nil
551+
hash[chr] += 1
552+
else
553+
hash[chr] = 1
554+
end
555+
end
556+
end
557+
558+
#字符最小频率hash转换为字符数组
559+
hash.keys.each do |key|
560+
for i in 0..hash[key] - 1
561+
result << key
562+
end
563+
end
564+
565+
return result
566+
end
567+
```
568+
521569
<p align="center">
522570
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
523571
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
(0)

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