如何实现获取生成指定字符串集合所需的最少单词数组
解决方案:生成覆盖所有输入字符串的最少单词数组
核心思路是统计每个单词在单条输入字符串中的最大出现次数,最终数组只需包含每个单词重复其最大次数的结果,就能组合出所有输入的字符串。
具体步骤:
- 遍历输入的每个字符串,将其拆分为单词数组
- 对每个拆分后的单词数组,统计当前字符串内各单词的出现次数
- 维护一个字典记录每个单词的最高出现次数:如果当前字符串中某单词的次数比字典里记录的更高,就更新字典值
- 最后根据字典生成结果数组:每个单词重复对应最高次数后拼接起来
代码实现(C#)
因为你无法使用HashSet,可以用Dictionary<string, int>来替代,同样能完成唯一单词的统计和次数记录:
using System; using System.Collections.Generic; using System.Linq; public class Solution { public static string[] GetMinWordArray(string[] input) { // 字典:键为单词,值为该单词在单条输入中的最大出现次数 Dictionary<string, int> maxWordCounts = new Dictionary<string, int>(); foreach (string str in input) { // 拆分当前字符串为单词数组(按空格分割,自动忽略空字符串) string[] words = str.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); // 统计当前字符串内各单词的出现次数 Dictionary<string, int> currentCounts = new Dictionary<string, int>(); foreach (string word in words) { if (currentCounts.ContainsKey(word)) { currentCounts[word]++; } else { currentCounts[word] = 1; } } // 更新全局最大次数 foreach (var kvp in currentCounts) { if (maxWordCounts.ContainsKey(kvp.Key)) { if (kvp.Value > maxWordCounts[kvp.Key]) { maxWordCounts[kvp.Key] = kvp.Value; } } else { maxWordCounts[kvp.Key] = kvp.Value; } } } // 生成最终结果数组 List<string> result = new List<string>(); foreach (var kvp in maxWordCounts) { for (int i = 0; i < kvp.Value; i++) { result.Add(kvp.Key); } } return result.ToArray(); } // 测试示例 public static void Main() { string[] input = {"hi hello hello", "hello", "bye", "bye bye", "hello hello"}; string[] output = GetMinWordArray(input); // 输出结果:["bye", "bye", "hello", "hello", "hi"](顺序无关) Console.WriteLine(string.Join(", ", output)); } }
代码解释:
- 外层循环遍历每个输入字符串,拆分后统计当前字符串内的单词次数
- 对比当前次数和全局字典中的最大次数,更新最大值
- 最后遍历全局字典,将每个单词重复对应次数加入结果列表
- 结果数组顺序无关,符合题目要求
内容的提问来源于stack exchange,提问作者Angela Z.
相关产品推荐
相关产品推荐

