- 博客访问: 3746
- 博文数量: 6
- 博客积分: 0
- 博客等级: 民兵
- 技术积分: 75
- 用 户 组: 普通用户
- 注册时间: 2014-12-31 14:08
文章分类
全部博文(6)
- 面试题(2)
- 题目(1)
- 热点技术(1)
- 生活(2)
- 未分配的博文(0)
分类: Python/Ruby
2015-01-12 10:58:00
input: A
, A2, C2>, A3<>, A4< B4<>, C4>>
output:
A< B, C >
B2< C, D >
C2< D >
A2< B2< C, D >, C2< D > >
A3< >
B4< >
D4< E4 >
C4< D4< E4 > >
A4< B4< >, C4< D4< E4 > > >
python code:
-
#!/usr/bin/env python
-
-
class Template(object):
-
def __init__(self):
-
self.name = ""
-
self.args = []
-
-
def __str__(self):
-
return self.name + "< " + ", ".join([str(a) for a in self.args]) + " >"
-
__repr__ = __str__
-
-
def parse_template(ts):
-
tlist = []
-
stk = []
-
pos = 0
-
arg = ""
-
-
for i, c in enumerate(ts):
-
if c in "<>,":
-
if c == '<':
-
t = Template()
-
t.name = ts[pos : i].strip()
-
stk.append(t)
-
elif c == '>':
-
t = stk.pop()
-
arg = ts[pos : i].strip()
-
if arg:
-
t.args.append(arg)
-
if stk:
-
stk[-1].args.append(t)
-
#else:
-
tlist.append(t)
-
else: # comma
-
arg = ts[pos : i].strip()
-
if arg and stk:
-
stk[-1].args.append(arg)
-
pos = i + 1
-
return tlist
-
-
-
ts = input("input:")
-
tlist = parse_template(ts)
-
for t in tlist:
-
print(str(t))
C++ code:
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <string>
-
#include <stack>
-
#include <iostream>
-
-
using namespace std;
-
-
struct Temp
-
{
-
size_t name;
-
size_t start;
-
size_t end;
-
};
-
-
void print_temp(const string& temp)
-
{
-
stack<Temp> st;
-
size_t pos1 = 0;
-
size_t pos2 = 0;
-
-
while (pos1 < temp.size())
-
{
-
pos2 = temp.find_first_of("<,>", pos1);
-
if (pos2 == string::npos)
-
{
-
break;
-
}
-
-
if (temp.at(pos2) == '<')
-
{
-
Temp t;
-
t.name = pos1;
-
t.start = pos2;
-
t.end = string::npos;
-
st.push(t);
-
}
-
else if (temp.at(pos2) == '>')
-
{
-
if (st.empty())
-
{
-
// error
-
cout << "unmatched angle brackets" << endl;
-
break;
-
}
-
else
-
{
-
st.top().end = pos2;
-
Temp t = st.top();
-
st.pop();
-
cout << "name: " << temp.substr(t.name, t.start - t.name) << endl;
-
cout << "arg: " << temp.substr(t.start + 1, pos2 - t.start - 1) << endl;
-
}
-
}
-
else
-
{
-
// comma
-
}
-
-
pos1 = pos2 + 1;
-
}
-
-
if (!st.empty())
-
{
-
cout << "unmatched angle brackets" << endl;
-
}
-
}
-
-
int main(int argc, char **argv)
-
{
-
char lbuf[1024];
-
cin.getline(lbuf, sizeof(lbuf));
-
print_temp(lbuf);
-
-
return 0;
-
}