点击跳转题目
本题学到两点:
1.初始化数组,全部为0的简单写法。之前都是
int arr[26];
memset(arr,0,sizeof(arr));
2.if条件中的&&部分左右顺序不能颠倒。颠倒报错,之前一直没重视。
思路:
遍历s,push当前字符,如果当前的栈顶元素<=余下字符串中发最小字符,则pop并加到结果中。否则一直push到栈中。
class Solution {
public:string robotWithString(string s) {int arr[26]{}; //简单写法for(char c :s) arr[c-'a']++;stack<char> st;string ans;for(char c:s){int i=0;--arr[c-'a'];while(i<26 && arr[i]==0) i++;st.push(c);while(!st.empty() && st.top()-'a'<=i){ //顺序颠倒会报错,因为使用top()存在栈不空的前提ans+=st.top();st.pop();}}return ans;}};