[LeetCode] 248. Strobogrammatic Number III

Problem

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.

Example:

Input: low = "50", high = "100"
Output: 3
Explanation: 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.

Solution

class Solution {
    int count = 0;
    public int strobogrammaticInRange(String low, String high) {
        Map<Character, Character> map = new HashMap<>();
        map.put('0', '0');
        map.put('1', '1');
        map.put('6', '9');
        map.put('8', '8');
        map.put('9', '6');
        List<String> res = new ArrayList<>();
        for (int len = low.length(); len <= high.length(); len++) {
            dfs(map, low, high, new char[len], 0, len-1, res);
        }
        System.out.println(res);
        return count;
        
    }
    
    private void dfs(Map<Character, Character> map, String low, String high, char[] buffer, int left, int right, List<String> res) {
        if (left > right) {
            String num = new String(buffer);
            if ((num.length() == low.length() && num.compareTo(low) < 0) ||
               (num.length() == high.length() && num.compareTo(high) > 0)) {
                return;
            }
            count++;
            res.add(num);
            return;
        }
        
        for (char ch: map.keySet()) {
            if (buffer.length != 1 && left == 0 && ch == '0') continue;
            if (left == right && ch != map.get(ch)) continue;
            buffer[left] = ch;
            buffer[right] = map.get(ch);
            dfs(map, low, high, buffer, left+1, right-1, res);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值