Line and Word Counter using Hashing

 avatar
user_9350232
plain_text
9 months ago
1.2 kB
15
Indexable
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <string>
using namespace std;

int main() {
    unordered_map<string, int> lineHash;  // Hash map to store line -> frequency
    string line;
    int totalLines = 0, totalWords = 0;

    cout << "Enter text (type END to stop):\n";

    // Read lines until "END" is entered
    while (true) {
        getline(cin, line);
        if (line == "END")
            break;

        totalLines++;        // count line
        lineHash[line]++;    // store and count repeated line

        // Count words in this line
        stringstream ss(line);
        string word;
        while (ss >> word)
            totalWords++;
    }

    // Display results
    cout << "\n--- Result ---\n";
    cout << "Total Lines: " << totalLines << endl;
    cout << "Total Words: " << totalWords << endl;

    cout << "\nRepeated Line Frequency (using hashing):\n";
    for (auto &pair : lineHash) {
        cout << "\"" << pair.first << "\"  ->  " << pair.second << " time(s)\n";
    }

    cout << "\nTime Complexity: O(n * m)\n";
    cout << "Space Complexity: O(n)\n";
    return 0;
}
Editor is loading...
Leave a Comment