Java modified from II beat 97%


  • 0

    It is recursion dfs method, helper method slighted modified from II which was used to generate strobs of length n. It is used to count now. For the strob of the same length of low and high, use string compareTo to compare it.

    public class Solution {
        
        int count = 0;
        public int strobogrammaticInRange(String low, String high) {
            char[] map1 = {'0', '1', '8', '6', '9'};
            char[] map2 = {'0', '1', '8', '9', '6'};
            int lowLen = low.length();
            int highLen = high.length();
            for (int len = lowLen; len <= highLen; len++) {
                char[] strob = new char[len];
                helper(strob, map1, map2, 0, low, high);
            }
            return count;
        }
        
        
         private void helper(char[] strob, char[] map1, char[] map2, int pos, String low, String high) {
            int n = strob.length;
            int mid = (n - 1) / 2;
            int start = (pos != 0 || n == 1) ? 0 : 1;
            int end = n % 2 != 0 && pos == mid ? 2 : 4;
            for (int i = start; i <= end; i++) {
                strob[pos] = map1[i];
                strob[n - pos - 1] = map2[i];
                if (pos == mid) {
                    String strobStr = new String(strob);
                    if ((n > low.length() || low.compareTo(strobStr) <= 0) && (n < high.length() || high.compareTo(strobStr) >= 0)) {
                        count++; // 
                    }
                } else {
                    helper(strob, map1, map2, pos + 1, low, high);
                }
            }
        }
        
    }

Log in to reply
 

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