【发布时间】:2018-03-03 11:22:27
【问题描述】:
我已经尝试了几个小时来寻找一种方法来使用 C# 中的递归来确定两个字符串是否有一个共同的字母(唯一一个)...
例如,如果word1 是“hello”,word2 是“bye”,则它应该返回 true,因为只有一个“e”。然而,如果word1 是“hello”,word2 是“yellow”或“banana”,它应该返回false,因为“hello”和“yellow”之间有多个共同的字母,而在“香蕉”
这是我到目前为止所做的,但我不明白为什么它没有返回预期的结果:
private static bool didHaveOneCaracterInCommon(string word1, string word2, int index)
{
int indexChar = 0;
if(index + 1 < word1.Length)
indexChar = word2.IndexOf(word1[index]);
if (indexCar != -1) //There is at least one char in common
{
//Verify if there is another one character in common
if ( (index + 1 < word1.Length && didHaveOneCaracterInCommon(word1,word2.Remove(indexChar, 1), index + 1))
return false;
return true;
}
if (index + 1 == word1.Length)
return false;
return didHaveOneCaracterInCommon(word1, word2, index + 1);
}
提前谢谢你!
【问题讨论】:
-
你必须使用递归吗?使用 set 或 linq 可能更容易?
-
是的,我知道...我知道没有它会更容易,但是练习需要使用递归对函数进行编码
-
我用真实代码更新了我的伪代码并进行了测试
标签: c# string recursion char substring