# String Manipulation# Greedy# Input Processing

j011 - 11965 - Extra Spaces

🔗 前往 ZeroJudge 原題

題目描述

題目要求讀取多組測試案例,每組案例包含若干行字串。對於每一行字串,將連續的多個空格替換為單個空格,並輸出處理後的字串。

解題思路

程式碼逐行讀取輸入字串,並遍歷字串中的每個字符。如果當前字符是空格,則檢查前一個字符是否也是空格。如果是,則跳過當前空格;否則,輸出一個空格。如果當前字符不是空格,則直接輸出該字符。這樣可以確保連續的空格被壓縮為單個空格。

複雜度分析

  • 時間複雜度: O(N * M),其中 N 是測試案例的數量,M 是每行字串的長度。因為需要遍歷每一行字串中的每個字符。
  • 空間複雜度: O(1),程式碼只使用了常數級別的額外空間。

程式碼

#include <iostream>
using namespace std;
int n,t;
string s;
int main(){
	cin.tie(0); ios::sync_with_stdio(0);
	cin >> t;
	for(int ca=1;ca<=t;++ca){
		cin >> n;
		if(ca!=1)cout << "\n";
		cout << "Case " << ca << ":\n";
		getline(cin,s);
		for(int i=0;i<n;++i){
			getline(cin,s);
			bool sp=0;
			for(int j=0;j<s.size();++j){
				if(s[j]==' '){
					if(sp==0)cout << ' ';
					sp=1;
				}
				else{
					sp=0;
					cout << s[j];
				}
			}
			cout << "\n";
		}
	}
}

Discussion