leetcode - Reverse Words in a String
2014-03-08 19:18 张汉生 阅读(158) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 void reverseWords(string &); 4 }; 5 void Solution::reverseWords(string &s){ 6 int len = s.length(); 7 int i =0 ; 8 stack<string> st; 9 while (i<len){ 10 while (i<len && s[i]==' ') 11 i++; 12 string tmpStr=""; 13 while (i<len && s[i] != ' '){ 14 tmpStr += s[i]; 15 i++; 16 } 17 if (tmpStr.length()>0) 18 st.push(tmpStr); 19 } 20 s = ""; 21 while (!st.empty()){ 22 if (s.length()>0) 23 s += " "; 24 s += st.top(); 25 st.pop(); 26 } 27 }