2016-02-13 42 views
2

我應該做的是創建一個算法來計算一段文本中子字符串的數量,其中子字符串可以是字母B,後跟C或C由B.我不知道該怎麼做,但我試了一下,結果如下。我想知道我是否做得正確。蠻力:計算字符串數組中子字符串的個數

int substrCount(String S[0...n-1]){ 
    int count = 0; 
    for(int i = 0; i<=n-2; i++) 
    { 
     for(int j=i+1; j<i+2; j++) 
     { 
      if((S[i] == 'B' && S[j] == 'C') || (S[i] == 'C' 
       && S[j] == 'B')) 
      { 
       count = count + 1; 
      } 
     } 
    } 
} 

我會忽略它現在是否包含小寫或大寫。我還需要找到算法的複雜性,我相信它是O(n ^(2))。我做得對嗎?如果是這樣,我可以使它更高效嗎?

回答

2

這很適合我

static int substrCount(String str) { 
    int count=0; 
    for (int i=0; i<str.length()-1; i++) 
    { 
     boolean bc = (str.charAt(i) == 'B' && str.charAt(i+1) == 'C'); 
     boolean cb = (str.charAt(i) == 'C' && str.charAt(i+1) == 'B'); 
     if (bc || cb) { 
      count++; 
     } 
    } 
    return count; 
} 

您需要循環字符序列中字符串只是一次得到期望的結果。檢查兩個字符是否相等「BC」或「CB」,並將一個索引向前移動到字符串的末尾。

輸出例如:

"ACBAA" gives result 1 
"ABCBA" gives result 2 
"BCBCB" gives result 4 
"BBBBB" gives result 0 
相關問題