Skip to content

Instantly share code, notes, and snippets.

@egraldlo
Last active August 29, 2015 14:04
Show Gist options
  • Save egraldlo/6afd653a8b5aa3582f0b to your computer and use it in GitHub Desktop.
Save egraldlo/6afd653a8b5aa3582f0b to your computer and use it in GitHub Desktop.
reverse words in a string in leetcode
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
stack<string> stk;
int i=0;
int left=0;
int right=-1;
while(i<s.length()){
if(s.at(i)==' '){
left=right+1;
right=i;
stk.push(s.substr(left,right-left));
// cout<<s.substr(left,right-left)<<endl;
}
i++;
}
stk.push(s.substr(right+1,i-right));
// cout<<s.substr(right+1,i-right)<<endl;
int k=0;
while(!stk.empty()){
string ss=stk.top();
stk.pop();
// cout<<ss.c_str()<<endl;
int tmp=0;
while(tmp<ss.length()){
s[k++]=ss.at(tmp);
tmp++;
}
if(!stk.empty())
s[k++]=' ';
}
}
};
@egraldlo
Copy link
Author

egraldlo commented Aug 6, 2014

leetcode give a erroe info: "output limit exceeded"

@egraldlo
Copy link
Author

egraldlo commented Aug 6, 2014

line 21 cause wrong when input string is " ".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment