1. 程式人生 > >演算法設計與分析課作業【week7】leetcode--151. Reverse Words in a String

演算法設計與分析課作業【week7】leetcode--151. 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.

題目要求我們對字串中的單詞顛倒次序,需要注意的是需要去掉字串前後的空白字元,單詞與單詞之間出現多個空白字元時,也需要去掉多的空白字元,只剩下一個,也就是說我們需要注意以下情況:

  1.  字串只有空白字元 "      "   >>  更改後的字串為空字串。
  2. 字串前後有空白字元如:"    the sky is blue   "  >>  更改後的字串為 "blue is sky the"。
  3. 字串單詞之間有多個空白字元如:"the       sky is blue"。 >> 更改後的字串為"blue is sky the"。

我們首先除去字串前後的空白字元,再從第一個非空字元開始讀取字串,一旦讀到空白字元便可以存下該單詞(只要單詞不為空字串),然後將儲存單詞的變數清空,進行下一個單詞的讀取,如果有多個空白字元,之前儲存單詞是變數會是空字串,則跳過該空白字元,直至下一非空字串開始讀取,如此反覆讀取儲存後反向輸出即可。

C++程式碼如下:

class Solution {
public:
    void reverseWords(string &s) {
        string temp, result;
        int i = 0, j = s.length() - 1;
        //除去前後的空白字串
        while (i < s.length()) {
            if (s[i] == ' ')
                ++i;
            else 
                break;
        }
        while (j >= 0) {
            if (s[j] == ' ')
                --j;
            else 
                break;
        }
        for ( ; i <= j; ++i) {
            if (s[i] != ' ') {
                temp += s[i];
            }
            //解決出現多個空白字元的情況
            else if (temp != ""){
                result = " " + temp  + result;
                temp = "";
                
            }
        }
        if (temp != "") {
           result = temp + result; 
        }
        s = result;
    }
};