UVa 12416 – Excessive Space Remover
In text editors like Windows Notepad, how can you remove consecutive spaces? We can repeatedly use a "Replace All" operation to replace two consecutive spaces with one space (we consider this as one action). In this question, you need to simulate this process and report how many "Replace All" actions are required.
For example, if you want to remove consecutive spaces in "A very big joke.", you need two actions:
「A very big joke.」 -> 「A very big joke.」 -> 「A very big joke.」
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
Input is terminated by EOF. Each line contains letters, numbers, punctuation marks, and spaces (possibly leading spaces, but no trailing spaces). There are no TAB characters in the input. The input file size will not exceed 1MB. | For each line, print the number of actions required to remove all consecutive spaces. |
A very big joke. Goodbye! | 2 4 |
Thought Process
Use a While loop to perform actions. Each time running a For loop from left to right, add each character to a new string. **If the current character is a space and the next character is also a space, then skip the next space character by incrementing i+1**.
It is important to **not exceed the string length limit**, so when checking, **first check if you have reached the last character of the string**. Output the number of times the While loop runs -1.
Sample Code-ZeroJudge A520: Excessive Space Remover
#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 A520
//Dr. SeanXD