标签:style blog http color os io for ar art
题意:给你一个字符串,要求把它按语法转化成HTML格式。
分析:这题其实不难,就是一个递归的事情,当时忽略了括号嵌套的情况,所以一直WA,后来加上这种情况后就过了。简直醉了。
处理id和class时,在一个‘>‘内,先把遇到的id和class都push到一个容器中,然后再输出即可。
这题要注意的地方: 1.括号以及括号嵌套 2.好像没了
代码有点长,将就看吧。
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <string> #include <vector> using namespace std; string S; inline int StoNum(string str) { int num = atoi(str.c_str()); return num; } void print(int u,int v) { int i; if(u >= v) return; for(i=u;i<v;i++) { if(S[i] == ‘>‘) break; } int endi,sta = u; if(i == v) endi = v; else endi = i; if(S[u] == ‘(‘) { int cnt = 1; for(i=u+1;i<v;i++) { if(S[i] == ‘)‘ && cnt == 1) break; else if(S[i] == ‘)‘) cnt--; else if(S[i] == ‘(‘) cnt++; } sta = u+1; endi = i; print(sta,endi); print(endi+1,v); return; } int flag = 0; // 0:div 1:id 2:class 3:multi string divi = "",classi = "",idd = "",multi = ""; vector<string> cls,id; cls.clear(),id.clear(); vector<pair<int,int> > kuo; kuo.clear(); for(i=sta;i<endi;i++) { if(S[i] != ‘#‘ && S[i] != ‘*‘ && S[i] != ‘.‘ && S[i] != ‘(‘) { if(flag == 0) divi += S[i]; else if(flag == 1) idd += S[i]; else if(flag == 2) classi += S[i]; else if(flag == 3) multi += S[i]; } else if(S[i] == ‘#‘) // 0:div 1:id 2:class 3:multi { if(flag == 1) { id.push_back(idd); idd = ""; } else if(flag == 2) { cls.push_back(classi); classi = ""; } flag = 1; } else if(S[i] == ‘.‘) { if(flag == 1) { id.push_back(idd); idd = ""; } else if(flag == 2) { cls.push_back(classi); classi = ""; } flag = 2; } else if(S[i] == ‘*‘) { if(flag == 1) { id.push_back(idd); idd = ""; } else if(flag == 2) { cls.push_back(classi); classi = ""; } flag = 3; multi = ""; } else if(S[i] == ‘(‘) { int now; int cnt = 1; for(now=i+1;now<endi;now++) { if(S[now] == ‘)‘ && cnt == 1) break; else if(S[now] == ‘)‘) cnt--; else if(S[now] == ‘(‘) cnt++; } kuo.push_back(make_pair(i+1,now)); i = now; } } if(idd != "") id.push_back(idd); if(classi != "") cls.push_back(classi); int num = 1; if(multi != "") num = StoNum(multi); for(int k=0;k<num;k++) { cout<<"<"<<divi; if(id.size() != 0 || cls.size() != 0) cout<<" "; if(id.size()) { cout<<"id=\""; cout<<id[0]; for(i=1;i<id.size();i++) cout<<" "<<id[i]; cout<<"\""; } if(cls.size()) { if(id.size()) cout<<" "; cout<<"class=\""; cout<<cls[0]; for(i=1;i<cls.size();i++) cout<<" "<<cls[i]; cout<<"\""; } cout<<">"; if(kuo.size()) { for(i=0;i<kuo.size();i++) print(kuo[i].first,kuo[i].second); } print(endi+1,v); cout<<"</"<<divi<<">"; } } int main() { int n; scanf("%d",&n); while(n--) { cin>>S; print(0,S.length()); puts(""); } return 0; }
标签:style blog http color os io for ar art
原文地址:http://www.cnblogs.com/whatbeg/p/3930080.html