检查某个字符后面是否跟有另一个字符?

时间:2017-09-05 19:20:24

标签: c# for-loop boolean

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

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

例如:

AAZZBB = true

AAAXXXXYB = true

BBYYYXXXAXX = false

YYYBABYYYXXXAXX = false

这是我工作过的代码,但它一直都是真的:

 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;
        }

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

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²)的解决方案,但这解决了这个问题..

答案 2 :(得分:0)

您可以修改您的功能,如下例所示:

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;
}