https://leetcode.com/problems/reverse-words-in-a-string/
Given an input string, reverse the string word by word.
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.
代码:
class Solution { public: void reverseWords(string &s) { int len = s.length(); int newlen = 0; reverse(s.begin(), s.end()); for(int i = 0; i < len; i ++) { if(s[i] != ' ') { if(newlen != 0) s[newlen ++] = ' '; int temp = i; while(temp < len && s[temp] != ' ') s[newlen ++] = s[temp ++]; reverse(s.begin() + newlen - (temp - i), s.begin() + newlen); i = temp; } } s.resize(newlen); } };
$char$ 代码:
#include <bits/stdc++.h> using namespace std; char s[1010]; char ans[1010][30]; int main() { cin.getline(s, 1010); int len = strlen(s); s[len] = ' '; len ++; s[len] = '