File tree 3 files changed +85
-0
lines changed
lcci/01.06.Compress String
3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change @@ -136,6 +136,36 @@ func compressString(S string) string {
136
136
}
137
137
```
138
138
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
+
139
169
### ** ...**
140
170
141
171
```
Original file line number Diff line number Diff line change @@ -134,6 +134,36 @@ func compressString(S string) string {
134
134
}
135
135
```
136
136
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
+
137
167
### ** ...**
138
168
139
169
```
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments