Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.3 kB
6
Indexable
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>

using namespace std;

vector<int> autocomplete(vector<string>& commands) {
    unordered_map<string, int> command_indices;  // Map to store indices of previous commands
    vector<int> result;                          // Vector to store the indices of last displayed commands

    for (int idx = 0; idx < commands.size(); ++idx) {
        string current_command = commands[idx];
        string prefix = "";
        int last_displayed_idx = 0;  // Default to 0 if no common prefix is found

        for (int i = 0; i < current_command.length(); ++i) {
            prefix += current_command[i];
            if (command_indices.find(prefix) != command_indices.end()) {
                last_displayed_idx = command_indices[prefix];
            } else {
                break;  // No need to continue if no common prefix is found
            }
        }

        command_indices[prefix] = idx + 1;  // Store the current command's index
        result.push_back(last_displayed_idx);
    }

    return result;
}

int main() {
    vector<string> commands = {"100110", "1001", "1001111"};
    vector<int> result = autocomplete(commands);

    // Output the result
    for (int idx : result) {
        cout << idx << " ";
    }
    cout << endl;

    return 0;
}