Reverse Words in a String III Solutions in C++
Number 557
Difficulty Easy
Acceptance 70.0%
Link LeetCode
Other languages Go
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description//// Author : liuyubobobo/// Time : 2018-08-12#include <iostream>#include <vector>using namespace std;/// split and reverse/// Time Complexity: O(len(s))/// Space Complexity: O(n)class Solution {public:string reverseWords(string s) {vector<string> words;int start = 0;for(int i = start + 1; i <= s.size(); )if(i == s.size() || s[i] == ' '){words.push_back(s.substr(start, i - start));reverse(words.back().begin(), words.back().end());start = i + 1;i = start + 1;}elsei ++;if(words.size() == 0)return "";string res = words[0];for(int i = 1; i < words.size() ; i ++)res += " " + words[i];return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/reverse-words-in-a-string-iii/description//// Author : liuyubobobo/// Time : 2018-08-12#include <iostream>using namespace std;/// Reverse in place/// Time Complexity: O(len(s))/// Space Complexity: O(1)class Solution {public:string reverseWords(string s) {int start = 0;for(int i = start + 1; i <= s.size(); )if(i == s.size() || s[i] == ' '){reverse(s, start, i - 1);start = i + 1;i = start + 1;}elsei ++;return s;}private:void reverse(string& s, int start, int end){for(int i = start, j = end; i < j; i ++, j --)swap(s[i], s[j]);}};int main() {return 0;}