我正試圖通過我以前沒有見過的場景工作,並且正在努力想出一個算法來正確實施此操作。我的問題的一部分是對正確術語的朦朧回憶。我相信我所需要的是標準「組合」問題的變體,但我很可能離開那裏。帶字符替換的字符串組合
場景 給出的例子串"100"
(讓我們稱之爲x
),產生的x
該換出的那些0
(零)個字符一個用於o
(小寫O)的所有組合。因此,對於"100"
簡單的例子,我希望這樣的輸出:
"100"
"10o"
"1o0"
"1oo"
這將需要支持不同長度的字符串與不同0
個字符的數字,但假設永遠不會有超過5個的實例。
我有這個非常簡單的算法,我的"100"
樣的作品,但任何東西分崩離析更長/更復雜:
public IEnumerable<string> Combinations(string input)
{
char[] buffer = new char[input.Length];
for(int i = 0; i != buffer.Length; ++i)
{
buffer[i] = input[i];
}
//return the original input
yield return new string(buffer);
//look for 0's and replace them
for(int i = 0; i != buffer.Length; ++i)
{
if (input[i] == '0')
{
buffer[i] = 'o';
yield return new string(buffer);
buffer[i] = '0';
}
}
//handle the replace-all scenario
yield return input.Replace("0", "o");
}
我有一種揮之不去的感覺,遞歸可能是我的朋友在這裏,但我努力弄清楚如何將我需要的條件邏輯合併到這裏。
你不能只是有一個局部數組的位置的零,然後枚舉二進制數字與零和小o的二進制數字的替代? – 2015-03-02 21:01:23
@Meehm不確定我是否遵循你的意思,你能提供一個實現和/或額外的細節嗎? – 2015-03-02 21:05:00