-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0271_encode_and_decode_strings.rs
More file actions
71 lines (61 loc) · 1.58 KB
/
s0271_encode_and_decode_strings.rs
File metadata and controls
71 lines (61 loc) · 1.58 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#![allow(unused)]
struct Codec {
delimiter: &'static str,
delimiter_null: &'static str,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl Codec {
fn new() -> Self {
Self {
delimiter: "我",
delimiter_null: "你",
}
}
fn encode(&self, strs: Vec<String>) -> String {
if strs.len() == 0 {
return self.delimiter_null.to_string();
}
strs.join(self.delimiter)
}
fn decode(&self, s: String) -> Vec<String> {
if s == self.delimiter_null.to_string() {
return vec![];
}
s.split(self.delimiter)
.map(|x| x.to_string())
.collect::<Vec<String>>()
}
}
/**
* Your Codec object will be instantiated and called as such:
* let obj = Codec::new();
* let s: String = obj.encode(strs);
* let ans: VecVec<String> = obj.decode(s);
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_271() {
let strs = vec![
"leetcode is good".to_string(),
"codec object will".to_string(),
"instantiated allowed".to_string(),
];
let obj = Codec::new();
let s: String = obj.encode(strs);
println!("{}", s);
let ans: Vec<String> = obj.decode(s);
assert_eq!(
ans,
vec![
"leetcode is good".to_string(),
"codec object will".to_string(),
"instantiated allowed".to_string()
]
);
}
}