isaacpei / algorithm-interview

Weekly algorithm questions for interview
18 stars 0 forks source link

Q001_m75n_solution #10

Open 13o4t opened 6 years ago

13o4t commented 6 years ago

Question_ID: Q001

Language: Shell

Time Cost: 60-mins

Time Complexity: O(n)

Solution

  1. 先做个截断把 content 和 tag 分开
  2. 判断 tag 类型在行首加上缩进

My Code

echo '<a>123<b>456<c/></b></a>' | \                                                                                                              
awk -F '>' '{for(i=1;i<NF;++i)print $i">"}' | \                                                                                                  
sed 's/\(\w\+\)</\1\n</' | \                                                                                                                     
awk 'BEGIN {level=0}                                                                                                                             
     {                                                                                                                                           
        if(substr($0,1,2)=="</"){level--};                                                                                                       
        for(i=0;i<level;++i) printf "\t";                                                                                                        
        print $0;                                                                                                                                
        if(substr($0,1,1)=="<"&&substr($0,2,1)!="/"&&index($0,"/")!=length($0)-1){level++}                                                       
     }' 

Other

环境 Ubuntu 16.04

ryanorz commented 6 years ago

前来膜拜大佬

illuz commented 6 years ago

Make it more readable and it can run on in Mac. I hate sed in mac

echo '<a>123<b>456<c/></b></a>' | \
# > to >\n
awk -F '>' '{for(i=1;i<NF;++i)print $i">"}' | \
# </ to \n</
sed -E $'s/([[:alnum:]_])</\\1\\\n</g' | \
awk '
BEGIN {level = 0}
{
  if (substr($0,1,2) == "</") {
    level--;
  };
  for(i=0;i<level;++i) {
    printf "\t";
  }
  print $0
  if (substr($0,1,1) == "<" && substr($0,2,1) != "/" && index($0,"/") != length($0)-1) {
    level++;
  }
}'
rbee3u commented 6 years ago

瑟瑟发抖

biganans commented 6 years ago

瑟瑟发抖

isaacpei commented 6 years ago

不会shell的就看看不说话

KIDJourney commented 6 years ago

肛道理你们不能假设内容里面没有<, >这两个符号啊。