翻转数字题目总结
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
- 注意如果给的字符串长度是奇数时,中间的字母也需要进行检查
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) {