Skip to content

Commit a774cc7

Browse files
authored
feat: add solutions to lc problem: No.2434 (#4465)
No.2434.Using a Robot to Print the Lexicographically Smallest String
1 parent 58a5c21 commit a774cc7

File tree

7 files changed

+129
-235
lines changed

7 files changed

+129
-235
lines changed

solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README.md

Lines changed: 42 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -82,13 +82,13 @@ tags:
8282

8383
题目可以转化为,给定一个字符串序列,在借助一个辅助栈的情况下,将其转化为字典序最小的字符串序列。
8484

85-
我们可以用数组 `cnt` 维护字符串 $s$ 中每个字符的出现次数,用栈 `stk` 作为题目中的辅助栈,用变量 `mi` 维护还未遍历到的字符串中最小的字符。
85+
我们可以用数组 $\textit{cnt}$ 维护字符串 $s$ 中每个字符的出现次数,用栈 $\textit{stk}$ 作为题目中的辅助栈,用变量 $\textit{mi}$ 维护还未遍历到的字符串中最小的字符。
8686

87-
遍历字符串 $s$,对于每个字符 $c$,我们先将字符 $c$ 在数组 `cnt` 中的出现次数减一,更新 `mi`。然后将字符 $c$ 入栈,此时如果栈顶元素小于等于 `mi`,则循环将栈顶元素出栈,并将出栈的字符加入答案。
87+
遍历字符串 $s$,对于每个字符 $c$,我们先将字符 $c$ 在数组 $\textit{cnt}$ 中的出现次数减一,更新 $\textit{mi}$。然后将字符 $c$ 入栈,此时如果栈顶元素小于等于 $\textit{mi}$,则循环将栈顶元素出栈,并将出栈的字符加入答案。
8888

8989
遍历结束,返回答案即可。
9090

91-
时间复杂度 $O(n+C)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度,而 $C$ 为字符集大小,本题中 $C=26$。
91+
时间复杂度 $O(n + |\Sigma|)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度,而 $|\Sigma|$ 为字符集大小,本题中 $|\Sigma| = 26$。
9292

9393
<!-- tabs:start -->
9494

@@ -193,101 +193,59 @@ func robotWithString(s string) string {
193193

194194
```ts
195195
function robotWithString(s: string): string {
196-
let cnt = new Array(128).fill(0);
197-
for (let c of s) cnt[c.charCodeAt(0)] += 1;
198-
let min_index = 'a'.charCodeAt(0);
199-
let ans = [];
200-
let stack = [];
201-
for (let c of s) {
202-
cnt[c.charCodeAt(0)] -= 1;
203-
while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) {
204-
min_index += 1;
196+
const cnt = new Map<string, number>();
197+
for (const c of s) {
198+
cnt.set(c, (cnt.get(c) || 0) + 1);
199+
}
200+
const ans: string[] = [];
201+
const stk: string[] = [];
202+
let mi = 'a';
203+
for (const c of s) {
204+
cnt.set(c, (cnt.get(c) || 0) - 1);
205+
while (mi < 'z' && (cnt.get(mi) || 0) === 0) {
206+
mi = String.fromCharCode(mi.charCodeAt(0) + 1);
205207
}
206-
stack.push(c);
207-
while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) {
208-
ans.push(stack.pop());
208+
stk.push(c);
209+
while (stk.length > 0 && stk[stk.length - 1] <= mi) {
210+
ans.push(stk.pop()!);
209211
}
210212
}
211213
return ans.join('');
212214
}
213215
```
214216

215-
<!-- tabs:end -->
216-
217-
<!-- solution:end -->
218-
219-
<!-- solution:start -->
220-
221-
### 方法二
222-
223-
<!-- tabs:start -->
224-
225-
#### Python3
226-
227-
```python
228-
class Solution:
229-
def robotWithString(self, s: str) -> str:
230-
n = len(s)
231-
right = [chr(ord('z') + 1)] * (n + 1)
232-
for i in range(n - 1, -1, -1):
233-
right[i] = min(s[i], right[i + 1])
234-
ans = []
235-
stk = []
236-
for i, c in enumerate(s):
237-
stk.append(c)
238-
while stk and stk[-1] <= right[i + 1]:
239-
ans.append(stk.pop())
240-
return ''.join(ans)
241-
```
242-
243-
#### Java
217+
#### Rust
244218

245-
```java
246-
class Solution {
247-
public String robotWithString(String s) {
248-
int n = s.length();
249-
int[] right = new int[n];
250-
right[n - 1] = n - 1;
251-
for (int i = n - 2; i >= 0; --i) {
252-
right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1];
219+
```rust
220+
impl Solution {
221+
pub fn robot_with_string(s: String) -> String {
222+
let mut cnt = [0; 26];
223+
for &c in s.as_bytes() {
224+
cnt[(c - b'a') as usize] += 1;
253225
}
254-
StringBuilder ans = new StringBuilder();
255-
Deque<Character> stk = new ArrayDeque<>();
256-
for (int i = 0; i < n; ++i) {
257-
stk.push(s.charAt(i));
258-
while (
259-
!stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) {
260-
ans.append(stk.pop());
261-
}
262-
}
263-
return ans.toString();
264-
}
265-
}
266-
```
267226

268-
#### C++
227+
let mut ans = Vec::with_capacity(s.len());
228+
let mut stk = Vec::new();
229+
let mut mi = 0;
269230

270-
```cpp
271-
class Solution {
272-
public:
273-
string robotWithString(string s) {
274-
int n = s.size();
275-
vector<int> right(n, n - 1);
276-
for (int i = n - 2; i >= 0; --i) {
277-
right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1];
278-
}
279-
string ans;
280-
string stk;
281-
for (int i = 0; i < n; ++i) {
282-
stk += s[i];
283-
while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) {
284-
ans += stk.back();
285-
stk.pop_back();
231+
for &c in s.as_bytes() {
232+
cnt[(c - b'a') as usize] -= 1;
233+
while mi < 26 && cnt[mi] == 0 {
234+
mi += 1;
235+
}
236+
stk.push(c);
237+
while let Some(&top) = stk.last() {
238+
if (top - b'a') as usize <= mi {
239+
ans.push(stk.pop().unwrap());
240+
} else {
241+
break;
242+
}
286243
}
287244
}
288-
return ans;
245+
246+
String::from_utf8(ans).unwrap()
289247
}
290-
};
248+
}
291249
```
292250

293251
<!-- tabs:end -->

solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/README_EN.md

Lines changed: 44 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,15 @@ Perform second operation four times p=&quot;addb&quot;, s=&quot;&quot;, t=&quot;
8181

8282
### Solution 1: Greedy + Stack
8383

84-
The problem can be transformed into, given a string sequence, convert it into the lexicographically smallest string sequence with the help of an auxiliary stack.
84+
The problem can be transformed into: given a string sequence, use an auxiliary stack to convert it into the lexicographically smallest string sequence.
8585

86-
We can use an array `cnt` to maintain the occurrence count of each character in string $s$, use a stack `stk` as the auxiliary stack in the problem, and use a variable `mi` to maintain the smallest character in the string that has not been traversed yet.
86+
We can use an array $\textit{cnt}$ to maintain the count of each character in string $s$, use a stack $\textit{stk}$ as the auxiliary stack mentioned in the problem, and use a variable $\textit{mi}$ to keep track of the smallest character not yet traversed in the string.
8787

88-
Traverse the string $s$, for each character $c$, we first decrement the occurrence count of character $c$ in array `cnt`, and update `mi`. Then push character $c$ into the stack. At this point, if the top element of the stack is less than or equal to `mi`, then loop to pop the top element of the stack, and add the popped character to the answer.
88+
Traverse the string $s$. For each character $c$, first decrement its count in the array $\textit{cnt}$ and update $\textit{mi}$. Then push $c$ onto the stack. At this point, if the top element of the stack is less than or equal to $\textit{mi}$, repeatedly pop the top element from the stack and add it to the answer.
8989

90-
After the traversal ends, return the answer.
90+
After the traversal, return the answer.
9191

92-
The time complexity is $O(n+C)$, and the space complexity is $O(n)$. Here, $n$ is the length of the string $s$, and $C$ is the size of the character set, in this problem $C=26$.
92+
The time complexity is $O(n + |\Sigma|)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$ and $|\Sigma|$ is the size of the character set, which is $26$ in this problem.
9393

9494
<!-- tabs:start -->
9595

@@ -194,101 +194,59 @@ func robotWithString(s string) string {
194194

195195
```ts
196196
function robotWithString(s: string): string {
197-
let cnt = new Array(128).fill(0);
198-
for (let c of s) cnt[c.charCodeAt(0)] += 1;
199-
let min_index = 'a'.charCodeAt(0);
200-
let ans = [];
201-
let stack = [];
202-
for (let c of s) {
203-
cnt[c.charCodeAt(0)] -= 1;
204-
while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) {
205-
min_index += 1;
197+
const cnt = new Map<string, number>();
198+
for (const c of s) {
199+
cnt.set(c, (cnt.get(c) || 0) + 1);
200+
}
201+
const ans: string[] = [];
202+
const stk: string[] = [];
203+
let mi = 'a';
204+
for (const c of s) {
205+
cnt.set(c, (cnt.get(c) || 0) - 1);
206+
while (mi < 'z' && (cnt.get(mi) || 0) === 0) {
207+
mi = String.fromCharCode(mi.charCodeAt(0) + 1);
206208
}
207-
stack.push(c);
208-
while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) {
209-
ans.push(stack.pop());
209+
stk.push(c);
210+
while (stk.length > 0 && stk[stk.length - 1] <= mi) {
211+
ans.push(stk.pop()!);
210212
}
211213
}
212214
return ans.join('');
213215
}
214216
```
215217

216-
<!-- tabs:end -->
217-
218-
<!-- solution:end -->
219-
220-
<!-- solution:start -->
221-
222-
### Solution 2
223-
224-
<!-- tabs:start -->
225-
226-
#### Python3
227-
228-
```python
229-
class Solution:
230-
def robotWithString(self, s: str) -> str:
231-
n = len(s)
232-
right = [chr(ord('z') + 1)] * (n + 1)
233-
for i in range(n - 1, -1, -1):
234-
right[i] = min(s[i], right[i + 1])
235-
ans = []
236-
stk = []
237-
for i, c in enumerate(s):
238-
stk.append(c)
239-
while stk and stk[-1] <= right[i + 1]:
240-
ans.append(stk.pop())
241-
return ''.join(ans)
242-
```
243-
244-
#### Java
218+
#### Rust
245219

246-
```java
247-
class Solution {
248-
public String robotWithString(String s) {
249-
int n = s.length();
250-
int[] right = new int[n];
251-
right[n - 1] = n - 1;
252-
for (int i = n - 2; i >= 0; --i) {
253-
right[i] = s.charAt(i) < s.charAt(right[i + 1]) ? i : right[i + 1];
220+
```rust
221+
impl Solution {
222+
pub fn robot_with_string(s: String) -> String {
223+
let mut cnt = [0; 26];
224+
for &c in s.as_bytes() {
225+
cnt[(c - b'a') as usize] += 1;
254226
}
255-
StringBuilder ans = new StringBuilder();
256-
Deque<Character> stk = new ArrayDeque<>();
257-
for (int i = 0; i < n; ++i) {
258-
stk.push(s.charAt(i));
259-
while (
260-
!stk.isEmpty() && (stk.peek() <= (i > n - 2 ? 'z' + 1 : s.charAt(right[i + 1])))) {
261-
ans.append(stk.pop());
262-
}
263-
}
264-
return ans.toString();
265-
}
266-
}
267-
```
268227

269-
#### C++
228+
let mut ans = Vec::with_capacity(s.len());
229+
let mut stk = Vec::new();
230+
let mut mi = 0;
270231

271-
```cpp
272-
class Solution {
273-
public:
274-
string robotWithString(string s) {
275-
int n = s.size();
276-
vector<int> right(n, n - 1);
277-
for (int i = n - 2; i >= 0; --i) {
278-
right[i] = s[i] < s[right[i + 1]] ? i : right[i + 1];
279-
}
280-
string ans;
281-
string stk;
282-
for (int i = 0; i < n; ++i) {
283-
stk += s[i];
284-
while (!stk.empty() && (stk.back() <= (i > n - 2 ? 'z' + 1 : s[right[i + 1]]))) {
285-
ans += stk.back();
286-
stk.pop_back();
232+
for &c in s.as_bytes() {
233+
cnt[(c - b'a') as usize] -= 1;
234+
while mi < 26 && cnt[mi] == 0 {
235+
mi += 1;
236+
}
237+
stk.push(c);
238+
while let Some(&top) = stk.last() {
239+
if (top - b'a') as usize <= mi {
240+
ans.push(stk.pop().unwrap());
241+
} else {
242+
break;
243+
}
287244
}
288245
}
289-
return ans;
246+
247+
String::from_utf8(ans).unwrap()
290248
}
291-
};
249+
}
292250
```
293251

294252
<!-- tabs:end -->
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
impl Solution {
2+
pub fn robot_with_string(s: String) -> String {
3+
let mut cnt = [0; 26];
4+
for &c in s.as_bytes() {
5+
cnt[(c - b'a') as usize] += 1;
6+
}
7+
8+
let mut ans = Vec::with_capacity(s.len());
9+
let mut stk = Vec::new();
10+
let mut mi = 0;
11+
12+
for &c in s.as_bytes() {
13+
cnt[(c - b'a') as usize] -= 1;
14+
while mi < 26 && cnt[mi] == 0 {
15+
mi += 1;
16+
}
17+
stk.push(c);
18+
while let Some(&top) = stk.last() {
19+
if (top - b'a') as usize <= mi {
20+
ans.push(stk.pop().unwrap());
21+
} else {
22+
break;
23+
}
24+
}
25+
}
26+
27+
String::from_utf8(ans).unwrap()
28+
}
29+
}

solution/2400-2499/2434.Using a Robot to Print the Lexicographically Smallest String/Solution.ts

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
function robotWithString(s: string): string {
2-
let cnt = new Array(128).fill(0);
3-
for (let c of s) cnt[c.charCodeAt(0)] += 1;
4-
let min_index = 'a'.charCodeAt(0);
5-
let ans = [];
6-
let stack = [];
7-
for (let c of s) {
8-
cnt[c.charCodeAt(0)] -= 1;
9-
while (min_index <= 'z'.charCodeAt(0) && cnt[min_index] == 0) {
10-
min_index += 1;
2+
const cnt = new Map<string, number>();
3+
for (const c of s) {
4+
cnt.set(c, (cnt.get(c) || 0) + 1);
5+
}
6+
const ans: string[] = [];
7+
const stk: string[] = [];
8+
let mi = 'a';
9+
for (const c of s) {
10+
cnt.set(c, (cnt.get(c) || 0) - 1);
11+
while (mi < 'z' && (cnt.get(mi) || 0) === 0) {
12+
mi = String.fromCharCode(mi.charCodeAt(0) + 1);
1113
}
12-
stack.push(c);
13-
while (stack.length > 0 && stack[stack.length - 1].charCodeAt(0) <= min_index) {
14-
ans.push(stack.pop());
14+
stk.push(c);
15+
while (stk.length > 0 && stk[stk.length - 1] <= mi) {
16+
ans.push(stk.pop()!);
1517
}
1618
}
1719
return ans.join('');

0 commit comments

Comments
 (0)