• LeetCode Strobogrammatic Number III


    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    类似Strobogrammatic Number II. 从low.length()到high.length()长度范围内用Strobogrammatic Number II得到的所有结果算范围内个数.

    Time Complexity: O(len * 5^(len/2) * 5^(len/2)), len = high.length(), 第一个5^(len/2)是findHelper用时, 第二个5^(len/2)是iterate当前ls用时.

    Space: O(len/2  + 5^(len/2)), len/2层stack, 5^(len/2)是当前base的大小.

    AC Java:

     1 public class Solution {
     2     public int strobogrammaticInRange(String low, String high) {
     3         int count = 0;
     4         for(int len = low.length(); len<=high.length(); len++){
     5             List<String> ls = findHelper(len, len);
     6             for(String s : ls){
     7                 if((s.length() == low.length() && s.compareTo(low) < 0) || (s.length() == high.length() && s.compareTo(high) > 0)){
     8                     continue;
     9                 }
    10                 count++;
    11             }
    12         }
    13         return count;
    14     }
    15     
    16     private List<String> findHelper(int cur, int max){
    17         if(cur == 0){
    18             return new ArrayList<String>(Arrays.asList(""));
    19         }
    20         if(cur == 1){
    21             return new ArrayList<String>(Arrays.asList("0", "1", "8"));
    22         }
    23         
    24         List<String> res = new ArrayList<String>();
    25         List<String> base = findHelper(cur-2, max);
    26         for(String s : base){
    27             if(cur != max){
    28                 res.add("0" + s + "0");
    29             }
    30             res.add("1" + s + "1");
    31             res.add("8" + s + "8");
    32             res.add("6" + s + "9");
    33             res.add("9" + s + "6");
    34         }
    35         return res;
    36     }
    37 }

    类似Confusing Number II.

  • 相关阅读:
    如何删除.DS_Store文件?
    STL 技巧整理 7/22
    贪心
    防线
    bfs&dfs模板
    并查集学习总结
    二叉树相关代码
    区间DP学习笔记
    多算法模板整理
    防线题解
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/6273413.html
Copyright © 2020-2023  润新知