# String Manipulation# Input Parsing

e456 - Ten little Indians

🔗 前往 ZeroJudge 原題

題目描述

題目要求將輸入的以空白分隔的字串,按照 "One little, two little, three little Indians" 的格式輸出歌詞。輸入包含 2 到 30 個數字或形容詞。

解題思路

程式碼的主要邏輯是讀取輸入字串,並以空格作為分隔符號,將字串分割成多個單詞。然後,將每個單詞按照 "number little, " 的格式輸出,最後輸出最後一個單詞加上 "little Indians"。使用 getline 讀取整行輸入,然後遍歷字串,遇到空格就輸出前一個單詞,並清空單詞緩存。

複雜度分析

  • 時間複雜度: O(n),其中 n 是輸入字串的長度。需要遍歷整個輸入字串一次。
  • 空間複雜度: O(n),其中 n 是輸入字串的長度。b 字串最多可能存儲整個輸入字串。

程式碼

#include <iostream>
#include <string>
using namespace std;
int main(){
	string a;
	while(getline(cin,a)){
		string b;
		for(int i=0;i<a.length();i++){
			if(a[i]!=' '){
				b+=a[i];
			}
			else{
				cout << b << " little, ";
				b.clear();
			}
		}
		cout << b << " little Indians\n";
	}
}

Discussion