Leetcode 0248: 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.

Example 1:

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.

Time complexity: O(n)
沿用Leetcode 0247的思路,给出字符串长度n,我们可以通过递归找到长度为n的所有对称数。本题中我们枚举从low的长度到high的长度。在每次枚举中递归找到在该长度下的对称数 并且 满足 大于 low的值小于 high的值。以为本题要求只返回个数所以递归结果只需设为 int 。

class Solution {
    
    
    private static final char[][] PAIRS = new char[][] {
    
    
        {
    
    '0', '0'}, {
    
    '1', '1'}, {
    
    '6', '9'}, {
    
    '8', '8'}, {
    
    '9', '6'}};
    public int strobogrammaticInRange(String low, String high) {
    
    
        if(low == null || high == null || low.length() > high.length() 
           || (low.length() == high.length() && low.compareTo(high) > 0))
            return 0;
        int count = 0;
        for (int len = low.length(); len <= high.length(); len++) {
    
    
            count += dfs(low, high, new char[len], 0, len - 1);
        }
        return count;
    }
    
    private int dfs(String low, String high, char[] ch, int left, int right) {
    
    
        if (left > right) {
    
    
            String s = new String(ch);
            if ((ch.length == low.length() && s.compareTo(low) < 0)
                || (ch.length == high.length() && s.compareTo(high) > 0)) {
    
    
                return 0;
            } else {
    
    
                return 1;
            }
        }
        int count = 0;
        for(char[] p : PAIRS){
    
    
            ch[left] = p[0];
            ch[right] = p[1];
            if (ch.length != 1 && ch[0] == '0') {
    
    
                continue; 
            }
            if (left == right && (p[0] == '6' || p[0] == '9')) {
    
    
                continue; 
            }
            count += dfs(low, high, ch, left + 1, right - 1);
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113918097