medon3

HDNL Toy

Jan 15th, 2023
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3.  
  4. public class HDNL {
  5.  
  6. public static void main(String[] args) {
  7.  
  8.  
  9. Scanner sc = new Scanner(System.in);
  10.  
  11. int n = Integer.parseInt(sc.nextLine());
  12. Stack<Integer> ranks = new Stack<>();
  13. Stack<String> closingTags = new Stack<>();
  14. int indent = 0;
  15. StringBuilder output = new StringBuilder();
  16. for (int i = 0; i < n; i++) {
  17. String inputLine = sc.nextLine();
  18. int rank = Integer.parseInt(inputLine.substring(1));
  19.  
  20. while(!ranks.isEmpty() && ranks.peek()>=rank) {
  21. ranks.pop();
  22. String tag = closingTags.pop();
  23. indent--;
  24. printTag(output, indent, tag, "</%s>%n");
  25. }
  26.  
  27. printTag(output, indent,inputLine, "<%s>%n");
  28. indent++;
  29. ranks.push(rank);
  30. closingTags.push(inputLine);
  31.  
  32. }
  33. while (!closingTags.isEmpty()){
  34. String tag = closingTags.pop();
  35. indent --;
  36. printTag(output, indent,tag, "</%s>%n");
  37. }
  38.  
  39. System.out.println(output);
  40.  
  41. }
  42.  
  43. private static void printTag(StringBuilder output, int indent, String tag, String format){
  44.  
  45. for (int i = 0; i < indent; i++) {
  46. output.append(" ");
  47. }
  48. output.append(String.format(format,tag));
  49.  
  50. }
  51.  
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment