|
63 | 63 |
|
64 | 64 | <!-- solution:start --> |
65 | 65 |
|
66 | | -### Solution 1 |
| 66 | +### Solution 1: Simulation |
| 67 | + |
| 68 | +We classify all characters in string $s$ into two categories: "digits" and "letters", and put them into arrays $a$ and $b$ respectively. |
| 69 | + |
| 70 | +Compare the lengths of $a$ and $b$. If the length of $a$ is less than $b$, swap $a$ and $b$. Then check the difference in lengths; if it exceeds $1$, return an empty string. |
| 71 | + |
| 72 | +Next, iterate through both arrays simultaneously, appending characters from $a$ and $b$ alternately to the answer. After the iteration, if $a$ is longer than $b$, append the last character of $a$ to the answer. |
| 73 | + |
| 74 | +The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of string $s$. |
67 | 75 |
|
68 | 76 | <!-- tabs:start --> |
69 | 77 |
|
@@ -188,6 +196,80 @@ func reformat(s string) string { |
188 | 196 | } |
189 | 197 | ``` |
190 | 198 |
|
| 199 | +#### TypeScript |
| 200 | + |
| 201 | +```ts |
| 202 | +function reformat(s: string): string { |
| 203 | + let a: string[] = []; |
| 204 | + let b: string[] = []; |
| 205 | + |
| 206 | + for (const c of s) { |
| 207 | + if (c >= 'a' && c <= 'z') a.push(c); |
| 208 | + else if (c >= '0' && c <= '9') b.push(c); |
| 209 | + } |
| 210 | + |
| 211 | + if (Math.abs(a.length - b.length) > 1) { |
| 212 | + return ''; |
| 213 | + } |
| 214 | + |
| 215 | + if (a.length < b.length) { |
| 216 | + [a, b] = [b, a]; |
| 217 | + } |
| 218 | + |
| 219 | + const ans: string[] = []; |
| 220 | + |
| 221 | + for (let i = 0; i < b.length; i++) { |
| 222 | + ans.push(a[i] + b[i]); |
| 223 | + } |
| 224 | + |
| 225 | + if (a.length > b.length) { |
| 226 | + ans.push(a[a.length - 1]); |
| 227 | + } |
| 228 | + |
| 229 | + return ans.join(''); |
| 230 | +} |
| 231 | +``` |
| 232 | + |
| 233 | +#### Rust |
| 234 | + |
| 235 | +```rust |
| 236 | +impl Solution { |
| 237 | + pub fn reformat(s: String) -> String { |
| 238 | + let mut a: Vec<char> = Vec::new(); |
| 239 | + let mut b: Vec<char> = Vec::new(); |
| 240 | + |
| 241 | + for c in s.chars() { |
| 242 | + if c.is_ascii_lowercase() { |
| 243 | + a.push(c); |
| 244 | + } else if c.is_ascii_digit() { |
| 245 | + b.push(c); |
| 246 | + } |
| 247 | + } |
| 248 | + |
| 249 | + if (a.len() as i32 - b.len() as i32).abs() > 1 { |
| 250 | + return String::new(); |
| 251 | + } |
| 252 | + |
| 253 | + if a.len() < b.len() { |
| 254 | + std::mem::swap(&mut a, &mut b); |
| 255 | + } |
| 256 | + |
| 257 | + let mut ans = String::new(); |
| 258 | + |
| 259 | + for i in 0..b.len() { |
| 260 | + ans.push(a[i]); |
| 261 | + ans.push(b[i]); |
| 262 | + } |
| 263 | + |
| 264 | + if a.len() > b.len() { |
| 265 | + ans.push(a[a.len() - 1]); |
| 266 | + } |
| 267 | + |
| 268 | + ans |
| 269 | + } |
| 270 | +} |
| 271 | +``` |
| 272 | + |
191 | 273 | <!-- tabs:end --> |
192 | 274 |
|
193 | 275 | <!-- solution:end --> |
|
0 commit comments