ZeroJudge A520: Excessive Space Remover

題目敘述

本題採EOF方式收資料,每筆資料有一行含有空白字元的字串。如果有連續兩個空格的話,就將兩個空格刪減為一個空格,從左到右只要有做任何刪減就代表進行動作一次。要求輸出每個字串需要進行多少次動作。


範例輸入 #1

A very  big    joke.

         Goodbye!

範例輸出 #1

2

4


解題思路

使用While迴圈來進行動作,每次跑For迴圈從左到右判斷,如果目前字元為空格且下一個字元也是空格,則將 i+1 來跳過下一個空格字元,這邊需要注意不可以超過字串長度範圍,所以判斷時要先判斷目前是否已經跑到字串的最後一個字元。輸出跑While迴圈的次數-1即可。

解題程式碼如下 (僅供參考):

#include <iostream>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    string str;
    while (getline(cin, str))
    {
        bool stop = false;
        string newstr;
        int count = 0;
        while (!stop)
        {
            newstr = "";
            stop = true;
            for (int i = 0; i<str.length(); i++)
            {
                newstr += str[i];
                if (str[i] == ' ' && i+1<str.length() && str[i+1] == ' ')
                {
                    i++;
                    stop = false;
                }
            }
            str = newstr;
            count++;
        }
        cout << count-1 << "\n";
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天