Skip to content

Commit 960dcad

Browse files
authored
encode-and-decode-strings (#2769)
1 parent 3569f0c commit 960dcad

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// TC: O(n)
2+
// SC: O(n)
3+
impl Solution {
4+
pub fn encode(strs: Vec<String>) -> String {
5+
strs.iter()
6+
.map(|s| format!("{}#{}", s.len(), s))
7+
.collect()
8+
}
9+
10+
pub fn decode(s: String) -> Vec<String> {
11+
let mut strs = Vec::new();
12+
let bytes = s.as_bytes();
13+
let mut i = 0;
14+
while i < bytes.len() {
15+
let sep = s[i..].find('#').unwrap() + i;
16+
let len: usize = s[i..sep].parse().unwrap();
17+
strs.push(s[sep + 1..sep + 1 + len].to_string());
18+
i = sep + 1 + len;
19+
}
20+
strs
21+
}
22+
}

0 commit comments

Comments
 (0)