Java Solution with queue


  • 0
    Q
    List<String> results = new ArrayList<>();
    		if (digits == null || digits.length() == 0) {
    			return results;
    		}
    		String[] allDigits = new String[] {"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    		
    		
    		List<String> selectedDigitLetters = new ArrayList<>();
    		for (int i = 0; i < digits.length(); i++) {
    			int currentDigit = Character.getNumericValue(digits.charAt(i));
    			if (currentDigit == 1) {
    				return results;
    			} else {
    				String currentDigitLetters = allDigits[currentDigit - 1];
    				selectedDigitLetters.add(currentDigitLetters);
    			}
    		}
    		
    		LinkedList<String> queue = new LinkedList<>();
    		queue.add("");
    		int i = 0;
    		int totalLevel = selectedDigitLetters.size();
    		int currentLevel = 1;
    		int nextLevel = 0;
    		while (!queue.isEmpty() && i < totalLevel) {
    			String currentNode = queue.pollFirst();
    
    			String next = selectedDigitLetters.get(i);
    			for (int k = 0; k < next.length(); k++) {
    				queue.add(currentNode + next.charAt(k));
    				nextLevel++;
    			}
    			currentLevel--;
    			if (currentLevel == 0) {
    				currentLevel = nextLevel;
    				nextLevel = 0;
    				i++;
    			}
    		}
    		
    		String c = null;
    		while ((c = queue.pollFirst()) != null) {
    			results.add(c);
    		}
    		
    		return results;

Log in to reply
 

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