翻转数字题目总结

本文总结了关于翻转数字的编程题目,包括246. Strobogrammatic Number,247. Strobogrammatic Number II,248. Strobogrammatic Number III,1056. Confusing Number和1088. Confusing Number II。这些题目考察了判断数字在180度旋转后是否保持不变或变为有效数字,以及如何递归地生成这样的数字。解答时需要考虑数字对称性、递归策略和边界条件处理。
摘要由CSDN通过智能技术生成

246. Strobogrammatic Number

题目链接
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.

Example 1:

Input: “69”
Output: true
Example 2:

Input: “88”
Output: true
Example 3:

Input: “962”
Output: false


Abstract

  • 如果一个数字反转180后得到的数跟它本身相同,那么可以说这个数字是对称数。比如, 69 反转180后还是69
  • 据此推断一个数字是否是对称数

Idea
从数组两端开始依次检查每个字母对是否是对称的字母对

Question to ask
什么样的字母对是180度对称的?

Solution

  • 把已知的对称字符对放进map中,他们包括
        map.put('1', '1');
        map.put('8', '8');
        map.put('6', '9');
        map.put('9', '6');
  • 维护两个指针分别从两端开始向中心,检查当前指针所在的字母对是否是之前map所包含的对称字母对

Code

 public boolean isStrobogrammatic(String num) {
   
     Map<Character, Character> map = new HashMap<>();
     map.put('0', '0');
     map.put('1', '1');
     map.put('8', '8');
     map.put('6', '9');
     map.put('9', '6');
     
     int left = 0;
     int right = num.length() - 1;
     
     while(left <= right){
   
         char l = num.charAt(left);
         char r = num.charAt(right);
         // m1
         if (!map.containsKey(l) || map.get(l) != r){
   
             return false;
         }
         left++;
         right--;
     }
     return true;
 }

Time Complexity
O(n)

Space Complexity
O(1)
只存储对称的字母对,常数空间

Mistake

  1. 注意如果给的字符串长度是奇数时,中间的字母也需要进行检查

Summary

  • 如果题目比较抽象,可以举几个例子帮助理解
  • 注意处理一些边界的情况

247. Strobogrammatic Number II

题目链接
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).

Find all strobogrammatic numbers that are of length = n.

Example:

Input: n = 2
Output: [“11”,“69”,“88”,“96”]


Abstract

  • 找出长度为n的对称数字字符串

Idea

  • 已知那些字符对是对称的,根据这些字符对可以拼出符合要求长度的字符串
  • 可能要用到递归

Question to ask

  • 拼凑长度为奇数与长度为偶数的字符串过程中有什么不同?如何处理边界情况?
  • 如果使用递归,退出条件是什么?

Solution

  • 用递归解题,准备一个长度为n的字符数组,分别从两端开始填充,有左右两个指针记录当前要填充的字母位置
  • 退出条件:
    • 如果n为奇数,那么左右指针相等时,就是要填充中间字符的时候,这时候的选择有{0, 1, 8}
    • 如果n为偶数,那么左右指针重叠(left > right)时

Code

Map<Character, Character> map = new HashMap<>();
char[] middle = {
   '0', '1', '8'};

public List<String> findStrobogrammatic(int n) {
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值