fork download
  1. import java.util.regex.*;
  2.  
  3. class Uni {
  4. public static boolean isProperlyNested(String toTest) {
  5. int countOpen = 0;
  6. for (char c : toTest.toCharArray()) {
  7. if (c == '{') {
  8. countOpen++;
  9. } else if (c == '}') {
  10. countOpen--;
  11. if (countOpen < 0) return false;
  12. }
  13. }
  14. return countOpen == 0;
  15. }
  16. public static void main (String[] args) {
  17. String str1 = "{} {\n" +
  18. " {} {}\n" +
  19. "} // Properly nested",
  20. str2 = "{{\n" +
  21. " {{}}\n" +
  22. "} {} // Not properly nested";
  23. System.out.println(str1 + "\t" + isProperlyNested(str1));
  24. System.out.println(str2 + "\t" + isProperlyNested(str2));
  25. }
  26. }
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
{} {
    {} {}
} // Properly nested	true
{{
    {{}}
} {} // Not properly nested	false