isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q001_Leonhardt_solution #9

Open 1026742642 opened 6 years ago

1026742642 commented 6 years ago

Question_ID: Q001

Language: Java

Time Cost:

Time Complexity:

Solution

  1. 找出所有节点
  2. 根据<,</,/>的特征打印结果

My Code

public class Xml {
    public static void main(String[] args) {
        String xmlStr = "<a>123<b>456<c/></b></a>";
        String regEx = "(<\\w>|<\\/\\w>|(?<=>)\\w+(?=<)|<\\w\\/>)";
        Pattern pattern = Pattern.compile(regEx);
        Matcher m = pattern.matcher(xmlStr);
        String tab = "";
        while (m.find()){
            String temp = m.group();
            if (temp.contains("</")) {
                tab = tab.replaceFirst("\t", "");
                System.out.println(tab+temp);
            }else if (temp.contains("<") && !temp.contains("/")){
                System.out.println(tab+temp);
                tab += "\t";
            }else {
                System.out.println(tab+temp);
            }
        }
    }
}