LeetCode 2434. Using a Robot to Print the Lexicographically Smallest String
原题链接在这里:https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/
题目:
You are given a string s
and a robot that currently holds an empty string t
. Apply one of the following operations until s
and t
are both empty:
- Remove the first character of a string
s
and give it to the robot. The robot will append this character to the stringt
. - Remove the last character of a string
t
and give it to the robot. The robot will write this character on paper.
Return the lexicographically smallest string that can be written on the paper.
Example 1:
Input: s = "zza" Output: "azz" Explanation: Let p denote the written string. Initially p="", s="zza", t="". Perform first operation three times p="", s="", t="zza". Perform second operation three times p="azz", s="", t="".
Example 2:
Input: s = "bac" Output: "abc" Explanation: Let p denote the written string. Perform first operation twice p="", s="c", t="ba". Perform second operation twice p="ab", s="c", t="". Perform first operation p="ab", s="", t="c". Perform second operation p="abc", s="", t="".
Example 3:
Input: s = "bdda" Output: "addb" Explanation: Let p denote the written string. Initially p="", s="bdda", t="". Perform first operation four times p="", s="", t="bdda". Perform second operation four times p="addb", s="", t="".
Constraints:
1 <= s.length <= 105
s
consists of only English lowercase letters.
题解:
The point is to find the remaining smallest char. e.g."bdda", we need to find "a".
We first need to count the frequency of char in s.
Have a stack, move the current char to stack, if it is equal or smaller than remaining lowest char, then add it to the result.
Time Complexity: O(n). n = s.length(). each char is only in and out of stack once.
Space: O(n).
AC Java:
1 class Solution { 2 public String robotWithString(String s) { 3 Stack<Character> stk = new Stack<>(); 4 StringBuilder sb = new StringBuilder(); 5 int [] map = new int[26]; 6 char [] charArr = s.toCharArray(); 7 for(char c : charArr){ 8 map[c - 'a']++; 9 } 10 11 int low = 0; 12 for(char c : charArr){ 13 stk.push(c); 14 map[c - 'a']--; 15 while(low < 26 && map[low] == 0){ 16 low++; 17 } 18 19 while(!stk.isEmpty() && stk.peek() - 'a' <= low){ 20 sb.append(stk.pop()); 21 } 22 } 23 24 return sb.toString(); 25 } 26 }