'Algorithm to convert std::stack to std::string in C++ STL
In below C++ program I'm deleting a previous character considering '#' as a backspace character. I have used stack to build the string. Is there any C++ STL algorithm, which can help me to covert the std::stack to std::string. Any alternative to the code with 'while' loop.
string buildString(string s) {
stack<char> st;
for(auto a : s) {
if(a != '#') {
st.push(a);
}
else if(st.size()){
st.pop();
}
}
string result;
while(st.size()) {
result += st.top();
st.pop();
}
reverse(begin(result), end(result);
return result;
}
Solution 1:[1]
I'm deleting a previous character considering '#' as a backspace character. I have used stack to build the string.
You could do this without additional space like std::stack
:
std::string buildString(const std::string& s) {
std::string result;
for(auto a : s) {
if(a != '#') {
result += a;
}
else if(result.size()){
result.pop_back();
}
}
return result;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ramsay |