多行輸入,每行一篇小寫字母與空格組成的文章,# 結束。輸出每行不同單詞總數。
getline 讀整行。stringstream 自動按空白分割單詞。set 去重並計數。#includeusing namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string line; while (getline(cin, line) && line != "#") { stringstream ss(line); string word; unordered_set st; // O(1) 平均,比 set 更快 while (ss >> word) st.insert(word); cout << st.size() << '\n'; } return 0; }
stringstream 是 C++ 標準庫中處理字串分割的利器,支援 operator>> 直接讀單詞。unordered_set 平均 O(1) 插入查找,單詞總長度較小時常數更小。O(總字符數),單詞分割與哈希均為線性。O(單行不同單詞數)。