【问题标题】:Check if a certain character is followed by another character?检查某个字符后面是否跟着另一个字符?
【发布时间】:2017-09-05 19:20:24
【问题描述】:

如何检查字符串中某个字符后面是否跟着另一个字符?

我想检查字符串中的每个 'A' 后面是否至少有一个 'B'。 'B' 不必直接跟在它后面,也不必有偶数个 A 和 B。

例如:

AAZZBB = 真

AAAXXXXYB = 真

BBYYYXXXAXX = 假

YYYBABYYYXXXAXX = 假

这是我处理的代码,但它一直返回 true:

 public bool BalancedAB(string str)
        {
            int endPos = str.Length - 1;
            for (int pos = 0; pos <= endPos; pos++)
            {
                if (str[pos] == 'A')
                {
                    if (pos < endPos)
                    {
                        char next = str[pos + 1];

                        if (next == 'B')
                        {
                            pos++;
                            continue;
                        }
                    }

                    return true;
                }
            }

            return false;
        }

【问题讨论】:

  • 在这种情况下会返回什么:AZZBB?
  • if (str.LastIndexOf("A") != -1 &amp;&amp; str.IndexOf("B", str.LastIndexOf("A")) &gt; -1)
  • 这是一种非常糟糕的代码结构方式。使用continue 通常会散发出难闻的代码气味,并且历史上很少有应该使用continue 的情况。它错误地返回 true 并不让我感到惊讶。如果您到达 A 并且下一个字符不是 B 并且它不在字符串的末尾,那么它将返回 true。

标签: c# for-loop boolean


【解决方案1】:

您可以只检查一个字符的最后一个索引是否大于另一个字符的最后一个索引

(myString.IndexOf('A') > -1) && (myString.LastIndexOf('A') < myString.LastIndexOf('B'))

【讨论】:

  • 非常优雅的解决方案!
  • 边缘案例。 string myString = "B";我认为这个问题不清楚
  • @L.B - 好地方,我为这个案例的第一个字符添加了额外的检查
【解决方案2】:

此代码已用于您的测试用例:

bool HasABPairs(string word)
{
    for (int i = 0; i < word.Length; i++)
    {
        if (word[i] == 'A')
        {
            bool hasEquivalentB = false;

            for (int j = i + 1; j < word.Length; j++)
            {
                if (word[j] == 'B')
                {
                    hasEquivalentB = true;
                    break;
                }
            }

            if (!hasEquivalentB)
                return false;
        }
    }

    return true;
}

我认为可能有一个不是 O(n²) 的解决方案,但这解决了问题..

【讨论】:

    【解决方案3】:

    您可以修改您的函数,如下所示:

    public static bool BalancedAB(string str)
    {
        int endPos = str.Length - 1;
        for (int pos = 0; pos <= endPos; pos++)
        {
            if (str[pos] == 'A')
            {
                bool retValue = false;
                while (pos < endPos)
                {
                    if (str[pos + 1] != 'B') { pos++; }
                    else
                    {
                        retValue = true;
                        break;
                    }
                }
                if (!retValue) return false;
            }
        }
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-11
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      相关资源
      最近更新 更多