Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/d670ecb29da240131e5592cbdf56d1d6 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/d670ecb29da240131e5592cbdf56d1d6 to your computer and use it in GitHub Desktop.
class Solution {
inline char smallest(vector<int>& right_freq){
for(int i=0;i<26;++i){
if(right_freq[i]>0)
return char(97+i);
}
return 'z';
}
public:
string robotWithString(string s) {
int n=s.size();
vector<int> right_freq(26,0);
for(int i=0;i<n;++i)
right_freq[s[i]-'a']++;
string t, res;
int pos=0;
while(pos<n){
t.push_back(s[pos]);
right_freq[s[pos]-'a']--;
while(!t.empty() and t.back()<=smallest(right_freq)){
res.push_back(t.back());
t.pop_back();
}
pos++;
}
return res;
}
};
/*
//JAVA
import java.util.*;
class Solution {
private char smallest(int[] rightFreq) {
for (int i = 0; i < 26; ++i) {
if (rightFreq[i] > 0)
return (char) ('a' + i);
}
return 'z';
}
public String robotWithString(String s) {
int n = s.length();
int[] rightFreq = new int[26];
for (int i = 0; i < n; ++i) {
rightFreq[s.charAt(i) - 'a']++;
}
StringBuilder t = new StringBuilder();
StringBuilder res = new StringBuilder();
int pos = 0;
while (pos < n) {
t.append(s.charAt(pos));
rightFreq[s.charAt(pos) - 'a']--;
while (t.length() > 0 && t.charAt(t.length() - 1) <= smallest(rightFreq)) {
res.append(t.charAt(t.length() - 1));
t.deleteCharAt(t.length() - 1);
}
pos++;
}
return res.toString();
}
}
#Python
class Solution:
def smallest(self, right_freq):
for i in range(26):
if right_freq[i] > 0:
return chr(97 + i)
return 'z'
def robotWithString(self, s: str) -> str:
n = len(s)
right_freq = [0] * 26
for c in s:
right_freq[ord(c) - ord('a')] += 1
t = []
res = []
pos = 0
while pos < n:
t.append(s[pos])
right_freq[ord(s[pos]) - ord('a')] -= 1
while t and ord(t[-1]) <= ord(self.smallest(right_freq)):
res.append(t.pop())
pos += 1
return ''.join(res)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment