public class Main {
public static void main(String[] a) {
String s = "aa<a>123<b><c/>456<c/></b></a>aa";
for (int i = 0, length = s.length(), tabNum = 0; i < length; ) {
int end;
if (s.charAt(i) == '<') {
end = indexOf(s, ">", i, length);
if (s.charAt(i + 1) == '/')
print(s.substring(i, ++end), --tabNum);
else if (s.charAt(end - 1) == '/')
print(s.substring(i, ++end), tabNum);
else print(s.substring(i, ++end), tabNum++);
} else {
end = indexOf(s, "<", i, length);
print(s.substring(i, end), tabNum);
}
i = end;
}
}
static void print(String s, int tabNum) {
StringBuilder sb = new StringBuilder("\r\n");
while (tabNum-- > 0)
sb.append(" ");
sb.append(s);
System.out.print(sb);
}
static int indexOf(String s, String sub, int from, int ifNotFound) {
int i = s.indexOf(sub, from);
return i < 0 ? ifNotFound : i;
}
}
Question_ID: Q001_让奶牛飞_solution
Language: java
Time Cost: 90-mins
Time Complexity: O(n)
Solution
1.遍历字符串,每次打印一行 2.tabNum记录当前行应该有多少个tab,遇到开始标签tabNum+1,遇到结束标签tabNum-1
My Code