C#-如何使用递归确定两个字符串是否只有一个共同的字母

C#-如何使用递归确定两个字符串是否只有一个共同的字母,c#,string,recursion,char,substring,C#,String,Recursion,Char,Substring,几个小时以来,我一直在寻找一种方法,使用C#中的递归来确定两个字符串是否有一个相同的字母(仅一个) 例如,如果word1是“hello”,而word2是“bye”,它应该返回true,因为只有一个共同的“e”。但是,如果word1是“hello”,而word2是“yellow”或“banana”,则应返回false,因为“hello”和“yellow”之间有多个共同字母,“banana”中没有 这就是我目前所做的,但我不明白为什么它没有返回预期的结果: private static bool d

几个小时以来,我一直在寻找一种方法,使用C#中的递归来确定两个字符串是否有一个相同的字母(仅一个)

例如,如果
word1
是“hello”,而
word2
是“bye”,它应该返回
true
,因为只有一个共同的“e”。但是,如果
word1
是“hello”,而
word2
是“yellow”或“banana”,则应返回
false
,因为“hello”和“yellow”之间有多个共同字母,“banana”中没有

这就是我目前所做的,但我不明白为什么它没有返回预期的结果:

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);
}
private static bool didHaveOneCaracterInCommon(字符串字1、字符串字2、int索引)
{
int indexChar=0;
如果(索引+1

提前谢谢!

我建议用更清晰的基本情况稍微不同地处理它

private static bool charInCommon(string word1, string word2, int index)
    {
        int indexChar = 0;

            indexChar = word2.IndexOf(word1[index]);

        if (indexChar != -1)
        {
            return true;
        }
        return false;
    }

    private static bool onlyOneCaracterInCommon(string word1, string word2, int index = 0, bool commonfound = false)
    {
        if (index >= word1.Length) { return commonfound; }
        if (commonfound) //if you find another return false
        {
            if (charInCommon(word1, word2, index))
            { return false; }
        }
        else
        {
            if (charInCommon(word1, word2, index))
            { commonfound = true; }
            return onlyOneCaracterInCommon(word1, word2, index + 1, commonfound);
        }           
        return onlyOneCaracterInCommon(word1, word2, index + 1, commonfound);
    }
编辑:从伪代码更改为实代码

这里有两个基本情况:

编辑:将签名更改为
private static bool onlyoneracterincomon(string word1,string word2,int index=0,bool commonfound=false)

1) 到达绳子的末端
2) 到达两个字符串共享的第二个字符

你可以这样做

   public static bool ExclusiveCharInCommon(string l, string r)
    {
        int CharactersInCommon(string f, string s)
        {
            if (f.Length == 0) return 0;
            return ((s.IndexOf(f[0]) != -1) ? 1 : 0) + CharactersInCommon(f.Substring(1), s);
        }
        return CharactersInCommon(l, r) == 1;
    }

你必须使用递归吗?可能更容易使用set或linq?是的,我喜欢。。。我知道没有它会更容易,但是练习需要用递归来编写函数。我用真实代码更新了伪代码,并测试了它。
只有一个racterincomon(“hello”,“banana”,100,true)
-会返回true