检查字符串是否可以由C#中的另一个字符串的字符组成

Jav*_*ram 8 .net c# string

如果一个单词可以用另一个单词的字母组成,如何检查.每个字母只使用一次.

例:

如果str = "computer";那么

//if user enters below words output must be true
  comp
  put
  poet

//and if user enters below words output must be false
  count         // since n is not in str 
  root          // since there is only single o in str    
Run Code Online (Sandbox Code Playgroud)

Chr*_*man 5

这是一个基于计算每个字符数量的解决方案,然后检查第二个单词中每个字符的数量是否更少:

public static bool UsesSameLetters(string input, string check)
{
    var OriginalCounts = input.GroupBy(c => c)
        .ToDictionary(g => g.Key, g => g.Count());
    bool Success = check.GroupBy(c => c)
        .All(originalCounts.ContainsKey(g.Key) 
            && originalCounts[g.Key] >= g.Count);
    return Success;
}
Run Code Online (Sandbox Code Playgroud)

此解决方案计算输入字符串中每个字符的数量,然后检查检查字符串中的每个字符是否出现的次数少于输入字符串中的字符数.这个解决方案相当明确.


Jar*_*Par 3

以下应该可以解决问题

public static bool UsesSameLetters(string input, string check) {
  var array = new BitArray(check.Length, false);
  for (var i = 0; i < input.Length; i++) {   
    var found = false;
    for (var j = 0; j < check.Length; j++) {
      if (input[i] == check[j] && !array.Get(j)) {
        array.Set(j, true);
        found = true;
        break;
      }
    }
    if (!found) {
      return false;
    }
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 当长度不同时为什么返回“false”?如果 `input == "computer"` 且 `check == "poet"` 则该函数必须返回 `true` (3认同)