From 3933b49cb36eaacb1fca0d40861386722b32347e Mon Sep 17 00:00:00 2001 From: han Date: Wed, 26 Jul 2023 17:21:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A01002.=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=E5=B8=B8=E7=94=A8=E5=AD=97=E7=AC=A6=20Ruby=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1002.查找常用字符.md | 48 +++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/1002.查找常用字符.md b/problems/1002.查找常用字符.md index a53148b3..81b07b39 100644 --- a/problems/1002.查找常用字符.md +++ b/problems/1002.查找常用字符.md @@ -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 +``` +