Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Stack;
- public class HDNL {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = Integer.parseInt(sc.nextLine());
- Stack<Integer> ranks = new Stack<>();
- Stack<String> closingTags = new Stack<>();
- int indent = 0;
- StringBuilder output = new StringBuilder();
- for (int i = 0; i < n; i++) {
- String inputLine = sc.nextLine();
- int rank = Integer.parseInt(inputLine.substring(1));
- while(!ranks.isEmpty() && ranks.peek()>=rank) {
- ranks.pop();
- String tag = closingTags.pop();
- indent--;
- printTag(output, indent, tag, "</%s>%n");
- }
- printTag(output, indent,inputLine, "<%s>%n");
- indent++;
- ranks.push(rank);
- closingTags.push(inputLine);
- }
- while (!closingTags.isEmpty()){
- String tag = closingTags.pop();
- indent --;
- printTag(output, indent,tag, "</%s>%n");
- }
- System.out.println(output);
- }
- private static void printTag(StringBuilder output, int indent, String tag, String format){
- for (int i = 0; i < indent; i++) {
- output.append(" ");
- }
- output.append(String.format(format,tag));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment