[LeetCode] Reverse Words in a String

来源:互联网 发布:cbox网络电视去广告版 编辑:程序博客网 时间:2024/06/08 02:04

题目

Given an input string, reverse the string word by word.

给定一个输入字符串,逐个单词地翻转字符串。

For example,
Given s = “the sky is blue“,
return “blue is sky the“.

分析

最直观的的思路是先将字符串中单词反转,再将整个字符串翻转。这样的思路没有问题,但要考虑到多余空格。

思路

  1. 处理字符串前后多余空格。
  2. 遍历字符串剩余字符串,用单词填补空格,并将其翻转。
  3. 处理字符串中多余空白:翻转单词后,添加一个空格,遇到其他空格直接忽略。
  4. 调整字符串大小,翻转整个字符串。

代码

#include <iostream>#include <string>using namespace std;class Solution {public:    void reverseWord(string &s, int start, int end) {        while (start < end) {            char temp = s[start];            s[start++] = s[end];            s[end--] = temp;        }    }    void reverseWords(string &s) {        int start = 0, copy = 0;        int length = s.length();        int leftSpaces = 0, rightSpaces = 0;        for (int i = 0; i < length; i++) {            if (s[i] != ' ') {                break;             } else {                leftSpaces++;            }        }        if (leftSpaces == length) {            s = "";            return ;        }        for (int j = length - 1; j > 0; j--) {            if (s[j] != ' ') {                break;            } else {                rightSpaces++;            }        }         for (int i = leftSpaces; i < length - rightSpaces;) {             start = copy;            while (i < length - rightSpaces && s[i] != ' ') {                s[copy++] = s[i++];            }             reverseWord(s, start, copy - 1);            if (i < length - rightSpaces && copy > 0) {                s[copy++] = ' ';            }               while (i < length - rightSpaces && s[i] == ' ') {                i++;            }         }        s.resize(copy);        reverseWord(s, 0, copy - 1);    }};int main() {    Solution solution;    string s = "  abc   efg   ";    cout << "Result:" << s << "(start)"<<endl;      solution.reverseWords(s);    cout << "Result:" << s << "(end)"<<endl;  }