首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

HDU 2072 單詞數 — stringstream + set 一行搞定

     編輯:關於C++

題目

多行輸入,每行一篇小寫字母與空格組成的文章,# 結束。輸出每行不同單詞總數。

核心思路

  • getline 讀整行。
  • stringstream 自動按空白分割單詞。
  • set 去重並計數。

極簡 C++ 實作

#include 
using 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;
}

關鍵點

  1. stringstream 是 C++ 標準庫中處理字串分割的利器,支援 operator>> 直接讀單詞。
  2. unordered_set 平均 O(1) 插入查找,單詞總長度較小時常數更小。
  3. 題目無標點、純小寫,無需額外清洗。

複雜度

  • 時間:O(總字符數),單詞分割與哈希均為線性。
  • 空間:O(單行不同單詞數)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved