My Java solution, easy to understand


  • 2
    5
    public class Solution {
        private final static int[][] array = {{0, 0}, {1, 1}, {6, 9},
            {8, 8}, {9, 6}};
        private int count = 0;
        public int strobogrammaticInRange(String low, String high) {
            
            buildHelper("", low, high);
            buildHelper("0", low, high);
            buildHelper("1", low, high);
            buildHelper("8", low, high);
            
            return count;
        }
        
        private void buildHelper(String word, String low, String high) {
    
            if (word.length() >= low.length() && word.length() <= high.length()
                 && !(word.length() > 1 && word.charAt(0) == '0')) {
            	
            	if (!((word.length() == low.length() && word.compareTo(low) < 0) 
            				|| (word.length() == high.length() && word.compareTo(high) > 0))) {
            		count++;
            	}
            }
            
            if (word.length() + 2 > high.length()) {
                return;
            }
            
            for (int[] pair : array) {
                buildHelper(pair[0] + word + pair[1], low, high);
            }
        }
        
    }
    

    The idea is to construct numbers, if the current number is valid, increase the global counter by 1.


Log in to reply
 

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