From 6e3cf576e532b0c139c30960508e70fc7de30ae6 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 20 Feb 2025 22:54:00 +0800 Subject: [PATCH] feat: 17_letter_combinations_of_a_phone_number --- .../main.cpp | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 17_letter_combinations_of_a_phone_number/main.cpp diff --git a/17_letter_combinations_of_a_phone_number/main.cpp b/17_letter_combinations_of_a_phone_number/main.cpp new file mode 100644 index 0000000..ac10304 --- /dev/null +++ b/17_letter_combinations_of_a_phone_number/main.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution { + public: + unordered_map> charmap = { + {'2', {"a", "b", "c"}}, + {'3', {"d", "e", "f"}}, + {'4', {"g", "h", "i"}}, + {'5', {"j", "k", "l"}}, + {'6', {"m", "n", "o"}}, + {'7', {"p", "q", "r", "s"}}, + {'8', {"t", "u", "v"}}, + {'9', {"w", "x", "y", "z"}}, + }; + + unordered_set combineTwo(const unordered_set &a, const unordered_set &b) { + unordered_set result; + + for (auto first : a) { + for (auto second : b) { + result.insert(first + second); + } + } + + return result; + } + + vector letterCombinations(string digits) { + if (digits.length() == 0) return {}; + + unordered_set resultSet = charmap[digits[0]]; + + for (int i = 1; i < digits.length(); i++) { + resultSet = combineTwo(resultSet, charmap[digits[i]]); + } + + vector result; + for (auto s : resultSet) result.emplace_back(s); + + return result; + } +};