2011-11-08 32 views
2

這個問題很難,但我會試試。 我有我的4個字母mugo。我也有免費的字符串字(s)。
Let'say:ogoggmuogss。我正在尋找任何明智的方法來檢查我是否可以只使用我的字母來構造單詞(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** 

所以我的策略是把我的信給字符數組並刪除逐一檢查,建立字(小號)留下多少。但有沒有可能用幾行,我不知道 - 正則表達式?

+6

「有些人,當遇到一個問題,認爲「我知道,我會用正則表達式。」現在他們有兩個問題。「 - 傑米·薩溫斯基 – neeKo

+0

這可能會幫助:http://stackoverflow.com/questions/541954/ –

+0

只有10種類型的人在世界上:那些誰懂二進制和那些誰不 - 一點題外話:) – deadfish

回答

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; 
    } 
+0

這個LINQ很棒:)謝謝,先生! – deadfish

0

如果你的話的定義是可charactters的任意排列,那麼爲什麼你需要一個正則表達式?只要確保你使用每個字符一次。正則表達式不知道什麼是「正確的單詞」是,這是更好地避免你的算法使用無效字符不是利用他們使用正則表達式,以確保你沒有使用它們。

3

下面是一個簡單的方法: 對於您的源詞,創建一個大小爲26的數組,並用它來計算每個字母出現的次數。 對字典中的每個單詞都做同樣的事情。 然後比較兩者。 如果每個字母在詞典中的出現次數少於或等於源詞的次數,那麼它可以用於生成該詞。如果不是,那麼它不能。

C-Sharpish僞代碼:(可能是因爲寫不編譯)

/** 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; 
} 
+0

聲音甜:) – deadfish

+0

將它一些工作文字:) –

+0

@LB你可以修改它通過改變字母的大小和charToLetter功能其他拼音字母工作。因爲我不能快速識別哪些是哪些字母,我不確定這是簡體中文,繁體中文,日文漢字,平假名或片假名。但是如果它是其中的一個,那麼你可能也想切換到一個哈希表,否則你會有一個非常非常稀疏的數組來檢查。這會使代碼複雜一點,但是同樣的基本方法會起作用。 –

相關問題