isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q001_super2bai_solution #4

Open super2bai opened 6 years ago

super2bai commented 6 years ago

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

   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;
            }
        }
    }
rbee3u commented 6 years ago

讲真,,,贰佰的代码我认认真真看了10分钟,恁是没看懂

super2bai commented 6 years ago