Skip to content

Commit 9814270

Browse files
committed
feat: add rust solution to lcci problem: No.01.06
No.01.06.Compress String
1 parent dc86e00 commit 9814270

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

lcci/01.06.Compress String/README.md

+30
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,36 @@ func compressString(S string) string {
136136
}
137137
```
138138

139+
### **Rust**
140+
141+
```rust
142+
impl Solution {
143+
pub fn compress_string(s: String) -> String {
144+
let mut cs: Vec<char> = s.chars().collect();
145+
cs.push(' ');
146+
let mut res = vec![];
147+
let mut l = 0;
148+
let mut cur = cs[0];
149+
for i in 1..cs.len() {
150+
if cs[i] != cur {
151+
let count = (i - l).to_string();
152+
l = i;
153+
res.push(cur);
154+
cur = cs[i];
155+
for c in count.chars() {
156+
res.push(c);
157+
}
158+
}
159+
}
160+
if res.len() >= cs.len() - 1 {
161+
s
162+
} else {
163+
res.iter().collect()
164+
}
165+
}
166+
}
167+
```
168+
139169
### **...**
140170

141171
```

lcci/01.06.Compress String/README_EN.md

+30
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,36 @@ func compressString(S string) string {
134134
}
135135
```
136136

137+
### **Rust**
138+
139+
```rust
140+
impl Solution {
141+
pub fn compress_string(s: String) -> String {
142+
let mut cs: Vec<char> = s.chars().collect();
143+
cs.push(' ');
144+
let mut res = vec![];
145+
let mut l = 0;
146+
let mut cur = cs[0];
147+
for i in 1..cs.len() {
148+
if cs[i] != cur {
149+
let count = (i - l).to_string();
150+
l = i;
151+
res.push(cur);
152+
cur = cs[i];
153+
for c in count.chars() {
154+
res.push(c);
155+
}
156+
}
157+
}
158+
if res.len() >= cs.len() - 1 {
159+
s
160+
} else {
161+
res.iter().collect()
162+
}
163+
}
164+
}
165+
```
166+
137167
### **...**
138168

139169
```
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
impl Solution {
2+
pub fn compress_string(s: String) -> String {
3+
let mut cs: Vec<char> = s.chars().collect();
4+
cs.push(' ');
5+
let mut res = vec![];
6+
let mut l = 0;
7+
let mut cur = cs[0];
8+
for i in 1..cs.len() {
9+
if cs[i] != cur {
10+
let count = (i - l).to_string();
11+
l = i;
12+
res.push(cur);
13+
cur = cs[i];
14+
for c in count.chars() {
15+
res.push(c);
16+
}
17+
}
18+
}
19+
if res.len() >= cs.len() - 1 {
20+
s
21+
} else {
22+
res.iter().collect()
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)