Last active
August 29, 2015 14:04
-
-
Save egraldlo/6afd653a8b5aa3582f0b to your computer and use it in GitHub Desktop.
reverse words in a string in leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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++]=' '; | |
} | |
} | |
}; |
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
leetcode give a erroe info: "output limit exceeded"