【问题标题】:C# - How do I determine if two strings have only one single letter in common using recursionC# - 如何使用递归确定两个字符串是否只有一个共同的字母
【发布时间】: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


【解决方案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 onlyOneCaracterInCommon(string word1, string word2, int index = 0, bool commonfound = false) 所以你可以只用 word1 和 word2 调用它。

1) 到达字符串的末尾 2)到达两个字符串共有的第二个字符。

【讨论】:

  • onlyOneCaracterInCommon("hello", "banana", 100, true) - 将返回 true
【解决方案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;
    }

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2013-11-26
    • 2011-04-18
    • 2020-08-27
    相关资源
    最近更新 更多