From 7af9bce5772738150e0ba5b84947dfd26d92801e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=9E=97=E5=B3=B0?= Date: Fri, 2 Nov 2018 10:50:59 +0800 Subject: [PATCH] =?UTF-8?q?017.=20Letter=20Combinations=20of=20a=20Phone?= =?UTF-8?q?=20Number=20(=E7=94=B5=E8=AF=9D=E5=8F=B7=E7=A0=81=E7=9A=84?= =?UTF-8?q?=E5=AD=97=E6=AF=8D=E7=BB=84=E5=90=88)=20(java)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Solution.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 solution/017. Letter Combinations of a Phone Number/Solution.java diff --git a/solution/017. Letter Combinations of a Phone Number/Solution.java b/solution/017. Letter Combinations of a Phone Number/Solution.java new file mode 100644 index 0000000000000..6b4c9458dc62f --- /dev/null +++ b/solution/017. Letter Combinations of a Phone Number/Solution.java @@ -0,0 +1,30 @@ +class Solution { + public List letterCombinations(String digits) { + char[] cs = digits.toCharArray(); + List result = new ArrayList<>(); + for (char a : cs) { + char[] charArray; + switch (a) { + case '2': charArray = new char[]{'a','b','c'}; break; + case '3': charArray = new char[]{'d','e','f'}; break; + case '4': charArray = new char[]{'g','h','i'}; break; + case '5': charArray = new char[]{'j','k','l'}; break; + case '6': charArray = new char[]{'m','n','o'}; break; + case '7': charArray = new char[]{'p','q','r','s'}; break; + case '8': charArray = new char[]{'t','u','v'}; break; + case '9': charArray = new char[]{'w','x','y','z'}; break; + default: return null; + } + if (result.size() == 0) { + for (char aCharArray : charArray) result.add(String.valueOf(aCharArray)); + } else { + List cache = new ArrayList<>(); + for (String string : result) { + for (char aCharArray : charArray) cache.add(string + aCharArray); + } + result = cache; + } + } + return result; + } +}