如何检查字母是否在字符串中?

时间:2011-11-08 22:12:30

标签: c# string algorithm letters

要问这个问题很难,但我会尝试。 我有4个字母m u g o。我也有免费的字符串( s )。
让我们说:og ogg muogss。我正在寻找任何明智的方法来检查我是否可以仅使用我的字母来构造单词( s )。请注意我们曾使用过g我们无法再次使用它。

og - possible because we need only **g** and **o**
ogg - not possible we took **o** and **g**, need the second **g**
muogss - not possible we took all, need also additional **s**

所以我的策略是将我的信件带到char数组并逐个删除并检查剩下多少用于构建单词( s )。但是有可能以某种方式使用几行,我不知道 - 正则表达式?

3 个答案:

答案 0 :(得分:7)

你的方法只有几行...

   public static bool CanBeMadeFrom(string word, string letters)
    {
        foreach (var i in word.Select(c => letters.IndexOf(c, 0)))
        {
            if (i == -1) return false;
            letters = letters.Remove(i, 1);
        }
        return true;
    }

答案 1 :(得分:3)

这是一个简单的方法: 对于源词,创建一个大小为26的数组,并使用它来计算每个字母出现的次数。 对词典中的每个单词执行相同操作。 然后比较两者。 如果每个字母在字典单词中出现的次数少于或等于源字,那么它可用于制作该单词。如果没有,那就不行了。

C-Sharpish Pseudocode :(可能不按编写方式编译)

/** Converts characters to a 0 to 25 code representing alphabet position.
    This is specific to the English language and would need to be modified if used
    for other languages. */
int charToLetter(char c) {
    return Char.ToUpper(c)-'A';
}

/** Given a source word and an array of other words to check, returns all 
    words from the array which can be made from the letters of the source word. */
ArrayList<string> checkSubWords(string source, string[] dictionary) {

    ArrayList<string> output = new ArrayList<string>();

    // Stores how many of each letter are in the source word.
    int[] sourcecount = new int[26];  // Should initialize to 0, automatically
    foreach (char c in source) {
        sourcecount[c]++;
    }

    foreach (string s in dictionary) {

        // Stores how many of each letter are in the dictionary word.
        int[] dictcount = new int[26]; // Should initialize to 0, automatically
        foreach (char c in s) {
            dictcount[c]++;
        }

        // Then we check that there exist no letters which appear more in the 
        // dictionary word than the source word.
        boolean isSubword = true;
        for (int i=0;i<26;i++) {
            if (dictcount[i] > sourcecount[i]) {
                isSubword = false;
            }
        }

        // If they're all less than or equal to, then we add it to the output.
        if (isSubWord) {
            output.add(s);
        }
    }
    return output;
}

答案 2 :(得分:0)

如果您对单词的定义是可用的字符串的任意排列,那么为什么需要正则表达式?只需确保您使用每个字符一次。正则表达式不知道“正确的单词”是什么,最好避免使用算法使用无效字符而不是使用 AND 使用正则表达式来确保你没有不要使用它们。

相关问题