2016-12-28 20 views
0

檢查是否使用規定的規則集形成字符串。使用以下規則生成:檢查是否使用規定的規則集形成字符串

a。該字符串以'a'開頭

b。每個'a'後面沒有任何內容或「a」或「bb」

c。每個 「BB」 後面是什麼或 'A'

我嘗試下面的代碼:

public static void main(String[] args) { 

    Scanner scn = new Scanner(System.in); 
    String str = scn.nextLine(); 
    boolean b = false; 
    if (str.charAt(0) == 'a') { 
     if (str.charAt(1) == 'b') { 
      if (str.charAt(2) == 'b') { 
       b = true; 
      } else 
       b = false; 

     } else 
      b = false; 
    } else 
     b = false; 
    System.out.println(b); 
} 

是代碼沒事... ??? 對於input = aab,輸出應該是false,對於input = abba,輸出應該是true。

+0

此問題是否屬於這裏:http://codereview.stackexchange.com/ – ItamarG3

+1

您是否嘗試過運行代碼?你的結果是什麼? – PrestonM

+0

爲上述兩個測試案例,它工作正常,但是當我在網上編碼網站上嘗試此代碼時,它正在下降某些測試案例,我不知道爲什麼。 –

回答

0

如果允許正則表達式,模式(a+(bb)?)+匹配遵循規則的字符串(並且不匹配不匹配的字符串)。

否則,由於字符串aaaaaaaaaaa與模式匹配,因此您的方法無法在沒有某種循環的情況下工作。

考慮下面的方法,它應該處理它。

private static boolean stringMatches(String s) { 
    // Handle empty and null cases first. 
    if (s == null || s.isEmpty()) return false; 

    // So long as the string continues to match the pattern, keep stripping 
    // characters from it until it is empty. If you reach empty, it matches the pattern. 
    while (! s.isEmpty()) { 
    // If the first character isn't 'a', we don't match; return false. 
    if (s.charAt(0) != 'a') { 
     return false; 
    } 

    // Check for abb, if so strip all of that, otherwise strip just the a 
    if (s.length() >= 3 && "abb".equals(s.substring(0,3)) { 
     s = s.substring(3); 
    } else { 
     s = s.substring(1); 
    } 
    } 
    // Reached empty string, return true. 
    return true; 
} 
+0

是的你是對的我應該使用循環,沒有來到我的腦海,因爲我只是看到了這兩個測試用例,並試圖對它進行編碼。 –