LeetCode: Strobogrammatic Number III

/**
Strobogrammatic Number III
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to count the total strobogrammatic numbers that exist in the range of low <= num <= high.
For example,
Given low = "50", high = "100", return 3. Because 69, 88, and 96 are three strobogrammatic numbers.
Note: Because the range might be a large number, the low and high numbers are represented as string.
Tips:
Construct char array from lenLow to lenHigh and increase count when s is between low and high. Add the stro pairs from outside to inside until left > right.
*/

public class StrobogrammaticNumberIII{

static char[][] pairs = {{'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'}};
    static int count = 0;

public static int strobogrammaticInRange(String low, String high){
for(int len = low.length(); len<=high.length(); len++){
dfs(low, high, new char[len], 0, len-1);
}
return count;
}

public static void dfs(String low, String high, char[] chars, int left, int right){
//exit condition
if(left>right){
String s = new String(chars);
//if the length is beyond the low and high values, exit
if((s.length()==low.length() && s.compareTo(low)<0) ||(s.length()==high.length() && s.compareTo(high)>0)){
return;
}
count++;
return;
}
//use the pairs to build the string from two ends
for(char[] p:pairs){
chars[left] = p[0];
chars[right] = p[1];
//if it starts with 0
if(chars.length!=1 && chars[0]=='0'){
continue;
}
if(left<right || left==right && p[0]==p[1]){
dfs(low, high, chars, left+1, right-1);
}
}
}

public static void main(String[] args){
String low="50", high="99";
System.out.println(strobogrammaticInRange(low, high));
}

}

No comments:

Post a Comment