Open super2bai opened 6 years ago
Question_ID: Q001
Language: Java
Time Cost: Oops...I don't remember
Time Complexity: O(n)
First...find < Then...find > And... split > and text
public static void main(String[] args) throws Exception { //测试用例 String s = "<a><b>456</b></a>"; // String s = "<a>123<b><c/></b></a>"; // String s = "<a>123<b>456<c/></b></a>"; // String s="<a></a>"; /** * 0:开头;1:<b/>;2:value;3:</b> * 工作中写代码需要把type提为Enum */ int type = -1; String indentStandard = " "; String indentInUse = ""; String[] left = s.split("\\<"); for (int i = 1; i < left.length; i++) { //结尾标签 if (left[i].startsWith("/")) { if (type != 0) { indentInUse = indentInUse.equals("") ? "" : indentInUse.substring(indentStandard.length()); } type = 3; if(left[i].endsWith(">")){ System.out.println(indentInUse + "<" + left[i]); }else { System.out.println(indentInUse + "<" + left[i].substring(0, left[i].indexOf(">") + 1)); System.out.println(indentInUse + left[i].substring(left[i].indexOf(">") + 1)); } } //<b/> else if (left[i].endsWith("/>")) { if (type != 2) { type = 1; indentInUse += indentStandard; } System.out.println(indentInUse + "<" + left[i]); } //<b> else if (left[i].endsWith(">")) { if (type == 0) { indentInUse += indentStandard; } System.out.println(indentInUse + "<" + left[i]); type = 0; } //<b>123 else { if (type == 0) { indentInUse += indentStandard; } System.out.println(indentInUse + "<" + left[i].substring(0, left[i].indexOf(">") + 1)); indentInUse += indentStandard; System.out.println(indentInUse + left[i].substring(left[i].indexOf(">") + 1)); type = 2; } } }
讲真,,,贰佰的代码我认认真真看了10分钟,恁是没看懂
一行未经格式化的xml
<分割后,变为a>111,/a>
<
a>111,/a>
把a>111,按照>的位置截取出节点和值,添加缩进的空格后输出。
a>111
>
split写了\\<,其它地方没有写\\,是因为split处是正则的规则,其它地方是普通字符串
\\<
\\
按照<分割的,分割后数组里面的值没有<,例如a>,输出的时候需要追加上<
a>
Question_ID: Q001
Language: Java
Time Cost: Oops...I don't remember
Time Complexity: O(n)
Solution
First...find < Then...find > And... split > and text
My Code