-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode_and_decode_strings.rs
55 lines (51 loc) · 1.27 KB
/
encode_and_decode_strings.rs
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
52
53
54
55
#![allow(dead_code)]
pub fn encode(strs: Vec<String>) -> String {
let mut result = String::new();
for s in strs {
result.push_str(&format!("{}{}", s.len(), s));
}
result
}
pub fn decode(s: String) -> Vec<String> {
let mut result = Vec::new();
let mut i = 0;
while i < s.len() {
let mut j = i;
while j < s.len() && s.chars().nth(j).unwrap().is_digit(10) {
j += 1;
}
let len = s[i..j].parse::<usize>().unwrap();
result.push(s[j..j + len].to_string());
i = j + len;
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_encode() {
let strs = vec![
"Hello".to_string(),
"World".to_string(),
"How".to_string(),
"Are".to_string(),
"You".to_string(),
];
assert_eq!(encode(strs), "5Hello5World3How3Are3You".to_string());
}
#[test]
fn test_decode() {
let s = "5Hello5World3How3Are3You".to_string();
assert_eq!(
decode(s),
vec![
"Hello".to_string(),
"World".to_string(),
"How".to_string(),
"Are".to_string(),
"You".to_string(),
]
);
}
}