151. Reverse Words in a String
Posted gsz-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了151. Reverse Words in a String相关的知识,希望对你有一定的参考价值。
题目描述:
Example:
Input: "the sky is blue
", Output: "blue is sky the
".
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up: For C programmers, try to solve it in-place in O(1) space.
解题思路:
题目不难,直接代码
代码:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 reverse(s.begin(), s.end()); 5 istringstream sin(s); 6 string word, res; 7 while (sin>>word) { 8 reverse(word.begin(), word.end()); 9 res += word; 10 res += " "; 11 } 12 if (res.size() > 0) 13 res.erase(res.size() - 1, 1); 14 s = res; 15 } 16 };
以上是关于151. Reverse Words in a String的主要内容,如果未能解决你的问题,请参考以下文章
151. Reverse Words in a String
151. Reverse Words in a String
151. Reverse Words in a String
leetcode-Reverse Words in a String-151