2017-09-05 59 views
-2

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

我想检查一个字符串中的每个'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; 
     } 
+1

在这种情况下返回什么:'AZZBB'? –

+0

'if(str.LastIndexOf(“A”)!= -1 && str.IndexOf(“B”,str.LastIndexOf(“A”))> -1)' – Vikhram

+0

这是一个很糟糕的方式来构造代码。使用“继续”通常会产生不良的代码味道,历史上应该使用“继续”的情况很少。我并不惊讶它错误地返回了“真实”。如果你到达'A'并且下一个字符不是'B'并且它不在字符串的末尾,那么它将返回true。 –

回答

3

你可以只检查一个字符的最后一个索引是比其他

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

非常优雅的解决方案! –

+0

边缘情况。 'string myString =“B”;'我认为这个问题不清楚 –

+0

@ L.B - 好点,我为这个案例的第一个字符添加了额外的检查 – Sayse

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²),但是这解决了问题..

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; 
} 
相关问题