From a36d5b7c1237c9b7d1f5e2170bfc07bf72e53f3d Mon Sep 17 00:00:00 2001 From: pezy_mbp Date: Fri, 2 Jan 2015 22:36:46 +0800 Subject: [PATCH] added 80. Letter Combinartions of a Phone Number --- .../README.md | 42 +++++++++++++++++++ .../main.cpp | 10 +++++ .../solution.h | 34 +++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 80. Letter Combinations of a Phone Number/README.md create mode 100644 80. Letter Combinations of a Phone Number/main.cpp create mode 100644 80. Letter Combinations of a Phone Number/solution.h diff --git a/80. Letter Combinations of a Phone Number/README.md b/80. Letter Combinations of a Phone Number/README.md new file mode 100644 index 0000000..9596100 --- /dev/null +++ b/80. Letter Combinations of a Phone Number/README.md @@ -0,0 +1,42 @@ +这道题有几个要理解透的地方: + +1. 0 和 1 的特殊性。这两个键并不对应字符,直接对应自身。 +2. 字典显然应该预备好,长度固定,角标明显,可以考虑用 array. +3. 例子输入有误导性:"Digit string "23"",其实输入的应该是 "23",吃亏才知道。 + +综上,这题不算什么好题。 + +----- + +结合 1 和 2 条,列出字典: + +```cpp +std::array map{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; +``` + +第一层循环,是迭代输入字符串: +```cpp +for (auto digit : digits) { + // 将按键数字转为 map 的角标, 最简单的方式就是用 digit - '0'. + for (auto c : map[digit - '0']) + // 我们希望第一层迭代的字符称为后面的前缀,如"23"中,"abc"应分别称为"def"的前缀。 +} +``` + +要实现前层成为后层的前缀,那么肯定需要三个 vector。分别存储前后,以及最终组合。 + +而后层,实际上是当前层,当前意味着临时性。前层是必须要存储住的,最终就更不消说了。 +所以可以考虑将前层与最终组合合并起来。那么用两个 vector 搞定。 + +```cpp +vector ret{""}; // 第一层没有前缀,所以留空。 +for (auto digit : digits) { + vector tmp; // 当前层。 + for (auto c : map[digit - '0']) + for (const auto &pre : ret) // 迭代前层,作为前缀 + tmp.push_back(pre + c); // 前缀 + 当前层字符 = 当前最终字符串 + ret = tmp; // 将临时的当前字符串赋给最终字符串(也是前层) +} +``` + +AC 后,发现该算法效率最高,且人数最多,更加凸显这道题并无太多意义。。。 diff --git a/80. Letter Combinations of a Phone Number/main.cpp b/80. Letter Combinations of a Phone Number/main.cpp new file mode 100644 index 0000000..ea7b3c1 --- /dev/null +++ b/80. Letter Combinations of a Phone Number/main.cpp @@ -0,0 +1,10 @@ +#include "solution.h" +#include + +int main() +{ + Solution s; + for (const auto &str : s.letterCombinations("23")) { + std::cout << str << std::endl; + } +} diff --git a/80. Letter Combinations of a Phone Number/solution.h b/80. Letter Combinations of a Phone Number/solution.h new file mode 100644 index 0000000..02501b1 --- /dev/null +++ b/80. Letter Combinations of a Phone Number/solution.h @@ -0,0 +1,34 @@ +// +// Solution.h +// Test +// +// Created by pezy on 12/27/14. +// Copyright (c) 2014 pezy. All rights reserved. +// + +#ifndef Test_Solution_h +#define Test_Solution_h + +#include +#include +#include + +using std::vector; using std::string; using std::array; + +class Solution { +public: + vector letterCombinations(string digits) { + vector ret{""}; + array map{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; + for (auto digit : digits) { + vector tmp; + for (auto c : map[digit - '0']) + for (const auto &pre : ret) + tmp.push_back(pre + c); + ret = tmp; + } + return ret; + } +}; + +#endif