Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit da789bd

Browse files
Create Using a Robot to Print the Lexicographically Smallest String.java
1 parent b962419 commit da789bd

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public String robotWithString(String s) {
3+
int[] counter = new int[26];
4+
for (char c : s.toCharArray()) {
5+
counter[c - 'a']++;
6+
}
7+
Stack<Character> stack = new Stack<>();
8+
StringBuilder sb = new StringBuilder();
9+
for (char c : s.toCharArray()) {
10+
stack.push(c);
11+
counter[c - 'a']--;
12+
while (!stack.isEmpty() && isSmallest(stack.peek(), counter)) {
13+
sb.append(stack.pop());
14+
}
15+
}
16+
while (!stack.isEmpty()) {
17+
sb.append(stack.pop());
18+
}
19+
return sb.toString();
20+
}
21+
22+
private boolean isSmallest(char c, int[] counter) {
23+
int limit = c - 'a';
24+
for (int i = 0; i < limit; i++) {
25+
if (counter[i] > 0) {
26+
return false;
27+
}
28+
}
29+
return true;
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /