My java iterator solution with Stack


  • 0
    W
    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> ret = new ArrayList<>();
            if(digits == null || digits.length() == 0) return ret;
            String[] dic = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            
            Stack<String> stack = new Stack<>();
            for(char c : dic[digits.charAt(0)-'0'].toCharArray()) {
                stack.push(""+c);
            }
            
            while(!stack.isEmpty()) {
                String path = stack.pop();
                if(path.length() == digits.length()) ret.add(path);
                else {
                    String neighbours = dic[digits.charAt(path.length())-'0'];
                    for(char c : neighbours.toCharArray()) {
                        stack.push(path+c);
                    }
                }
            }
            return ret;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.