1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
use std::collections::HashMap;
pub struct Element {
pub tag: String,
pub attributes: Vec<(String,String)>,
pub children: Vec<Element>,
}
pub struct Solution {
pub token: HashMap<String,i32>,
pub rev: HashMap<i32,String>,
}
impl Solution {
pub fn encode(&self, root: &Element) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
fn dfs(s: &Solution, e: &Element, out: &mut Vec<String>) {
out.push(s.token.get(&e.tag).unwrap().to_string());
for (k,v) in &e.attributes {
out.push(s.token.get(k).unwrap().to_string());
out.push(v.clone());
out.push("0".to_string());
}
out.push("0".to_string());
for c in &e.children { dfs(s,c,out); }
out.push("0".to_string());
}
dfs(self, root, &mut out);
out
}
pub fn decode(&self, tokens: &[String]) -> Element {
let mut idx = 0usize;
fn parse(s: &Solution, tokens: &[String], idx: &mut usize) -> Element {
let t = tokens[*idx].parse::<i32>().unwrap(); *idx += 1;
let mut e = Element { tag: s.rev.get(&t).unwrap().clone(), attributes: vec![], children: vec![] };
while tokens[*idx] != "0" {
let at = tokens[*idx].parse::<i32>().unwrap(); *idx += 1;
let mut parts = Vec::new();
while tokens[*idx] != "0" { parts.push(tokens[*idx].clone()); *idx += 1; }
*idx += 1;
e.attributes.push((s.rev.get(&at).unwrap().clone(), parts.join(" ")));
}
*idx += 1;
while tokens[*idx] != "0" { e.children.push(parse(s, tokens, idx)); }
*idx += 1;
e
}
parse(self, tokens, &mut idx)
}
}
|