如何忽略字符顺序判断字符串包含关系并移除对应字符
解决思路与实现
核心思路是基于字符计数处理这类忽略顺序的包含判断,因为问题本质是验证元素字符串的每个字符在容器中都有足够的出现次数,而非匹配连续子串。
步骤1:判断是否满足包含关系
- 分别统计两个字符串中每个字符的出现次数(用字典存储字符与对应计数)
- 遍历元素字符串的字符计数,逐一检查容器中对应字符的计数是否≥元素中的计数:
- 所有字符都满足则说明容器“包含”元素(忽略顺序)
- 只要有一个字符不存在或数量不足,就判定为不包含
步骤2:移除元素字符(若满足包含关系)
确认包含后,从容器字符串中移除元素的每个字符各一次:
- 基于容器的字符计数,减去元素的对应计数
- 遍历原容器字符串,根据剩余计数构建新字符串(保留原字符顺序)
C# 代码实现
using System; using System.Collections.Generic; using System.Text; public class StringProcessor { // 判断容器是否包含元素(忽略顺序),同时返回移除元素后的新字符串 public static bool TryRemoveElement(string container, string element, out string result) { result = container; // 统计容器的字符计数 var containerCounts = new Dictionary<char, int>(); foreach (char c in container) { containerCounts[c] = containerCounts.TryGetValue(c, out int count) ? count + 1 : 1; } // 统计元素的字符计数 var elementCounts = new Dictionary<char, int>(); foreach (char c in element) { elementCounts[c] = elementCounts.TryGetValue(c, out int count) ? count + 1 : 1; } // 检查包含条件 foreach (var pair in elementCounts) { if (!containerCounts.ContainsKey(pair.Key) || containerCounts[pair.Key] < pair.Value) return false; } // 更新容器计数,移除对应字符 foreach (var pair in elementCounts) { containerCounts[pair.Key] -= pair.Value; } // 构建结果字符串 var sb = new StringBuilder(); foreach (char c in container) { if (containerCounts[c] > 0) { sb.Append(c); containerCounts[c]--; } } result = sb.ToString(); return true; } // 测试示例 public static void Main() { string container = "WWGAAFWW"; string element = "WA"; if (TryRemoveElement(container, element, out string newContainer)) { Console.WriteLine($"包含,移除后结果:{newContainer}"); // 输出 WWGAFWWF } else { Console.WriteLine("不包含"); } } }
说明
- 计数法避免了排序的误区:排序后直接用
Contains无法解决问题(比如示例中排序后的元素是AW,容器排序后是AAFGWWWW,不存在连续的AW),而计数法能精准匹配字符数量需求。 - 构建结果时遍历原容器字符,可保留原字符串的字符顺序;若不需要原顺序,也可直接按剩余计数拼接字符。
内容的提问来源于stack exchange,提问作者Giorgio Tassinari
相关产品推荐
相关产品推荐

