首页 > 代码库 > LeetCode: Reverse Words in a String
LeetCode: Reverse Words in a String
LeetCode: Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
题目地址:https://oj.leetcode.com/problems/reverse-words-in-a-string/
算法:先把字符串分成一个一个word放在vector里面,然后在按逆序存入原来的字符串里。代码:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 vector<string> words = split(s); 5 s.clear(); 6 vector<string>::reverse_iterator iter = words.rbegin(); 7 if(iter != words.rend()){ 8 s += *iter; 9 ++iter;10 }11 for(; iter != words.rend(); ++iter){12 s += " ";13 s += *iter;14 }15 }16 vector<string> split(const string &s){17 string t;18 vector<string> words;19 string::const_iterator p = s.begin();20 while(p != s.end()){21 while(p != s.end() && isspace(*p)){22 ++p;23 }24 while(p != s.end() && !isspace(*p)){25 t.push_back(*p);26 ++p;27 }28 if(!t.empty()){29 words.push_back(t);30 t.clear();31 }32 }33 return words;34 }35 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。