fork download
  1. import java.util.*;
  2.  
  3. /*
  4. プログラミングのお題スレ Part15
  5. //mevius.5ch.net/test/read.cgi/tech/1564310397/32
  6.  
  7. > 32 名前:デフォルトの名無しさん[sage] 投稿日:2019/07/31(水) 17:25:11.51 ID:6BPSvdm1
  8. > プログラミングのお題スレ Part14
  9. > //mevius.5ch.net/test/read.cgi/tech/1558168409/981-986
  10. >
  11. > 漏れは、前スレの981 ではないですが、この問題の応用で、
  12. >
  13. > 括弧のネストの深さの最大値を求めよ
  14. >
  15. > 括弧の対応が取れていない場合は、-1 を出力せよ。
  16. > 2種類の括弧が順序通りに、閉じていないものも、-1 です
  17. >
  18. > ヒント : stack を使うと良いかも
  19. >
  20. > "" => 0
  21. > "( )" => 1
  22. > "{ ( { ( ) } ( ) ) } ( )" => 4
  23. >
  24. > "} {" => -1
  25. > "( { ) }" => -1
  26. */
  27. class Ideone
  28. {
  29. public static void main(String[] args)
  30. {
  31. try (Scanner in = new Scanner(System.in))
  32. {
  33. while (in.hasNextLine())
  34. {
  35. String line = in.nextLine();
  36. System.out.printf("\"%s\" => %d%n", line, countNest(line));
  37. }
  38. }
  39. }
  40.  
  41. static int countNest(String s)
  42. {
  43. int[] stack = new int[8];
  44. int count = 0;
  45. int max = 0;
  46.  
  47. for (int i = 0; i < s.length(); i++)
  48. {
  49. char c = s.charAt(i);
  50. int brackets = "({)}".indexOf(c);
  51. if (brackets == -1) continue;
  52. if ((brackets & 2) == 0)
  53. {
  54. if (count == stack.length) stack = Arrays.copyOf(stack, stack.length * 2);
  55. stack[count] = brackets & 1;
  56. if (++count > max) max = count;
  57. } else if (--count < 0 || (brackets & 1) != stack[count]) return -1;
  58. }
  59.  
  60. return count == 0 ? max : -1;
  61. }
  62. }
Success #stdin #stdout 0.1s 35392KB
stdin
( )
{ ( { ( ) } ( ) ) } ( )
} {
( { ) }
stdout
"( )" => 1
"{ ( { ( ) } ( ) ) } ( )" => 4
"} {" => -1
"( { ) }" => -1