Пробовал даже как рекомендуют в каментах ограничить вложенность, но не принимает.
package com.javarush.task.task19.task1918;
import java.io.*;
import java.nio.CharBuffer;
import java.util.*;
/*
Знакомство с тегами
*/
public class Solution {
public static void main(String[] args) {
String content = "";
ArrayList<String> tags = new ArrayList<String>();
LinkedList<Integer> queue = new LinkedList<>();
// String tag = "p";
// String fn = "/tmp/test.html";
String fn = "";
String tag = args[0];
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
fn = bufferedReader.readLine();
} catch (IOException e){
}
try (FileReader reader = new FileReader(fn)) {
char[] buffer = new char[1000000];
while (reader.ready()) {
int count = reader.read(buffer);
content += String.valueOf(buffer, 0, count);
}
} catch (IOException e) {
}
if (content == null) return;
content = content.replaceAll("\\n", "").replaceAll("\\r", "");
int opened = 0;
for (int i = content.indexOf("<" + tag); i < content.length() - tag.length() - 3; i++) {
String sub = content.substring(i, i + tag.length() + 3);
if (sub.startsWith("<" + tag + ">") || sub.startsWith("<" + tag + " ")) {
opened++;
if (opened <= 2) queue.push(i);
} else if (sub.equals("</" + tag + ">")) {
opened--;
if (opened < 2 ) queue.push(i + tag.length() + 3);
}
;
if (opened == 0) {
while (queue.size() > 0) {
tags.add(content.substring(queue.removeLast(), queue.removeFirst()));
}
}
}
while (tags.size() > 0)
System.out.println(tags.remove(0));
}
}