一、问题描述
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.
For example, the numbers "69", "88", and "818" are all strobogrammatic.
二、我的思路
旋转180度后一样,说明第一个数转到了最后一个,第二个到了倒数第二个...所以要用一个结构存某个数旋转后的数是什么,然后查看第n位和倒数第n位是否等价即可。我试用了hashmap,因为代码比较方便;n只判断到中间位置就完成了。停止条件要考虑一下奇偶,整合以后是i<(len+1)/2。
我的代码不该改成数字的。。。。
class Solution {
public boolean isStrobogrammatic(String num) {
if(num == null || num.length() == 0){
return true;
}
char[] array = num.toCharArray();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(6, 9);
map.put(9, 6);
map.put(8, 8);
map.put(1, 1);
map.put(0, 0);
for(int i = 0; i < (array.length+1)/2 ; i ++){
if(!map.containsKey(array[i] - '0') || map.get(array[i] - '0') != array[array.length-1-i] - '0'){
return false;
}
}
return true;
}
}
三、淫奇技巧
1)和我思路差不多,但是人家实现的好啊,直接比对Character。。
public boolean isStrobogrammatic(String num) {
Map<Character, Character> map = new HashMap<Character, Character>();
map.put('6', '9');
map.put('9', '6');
map.put('0', '0');
map.put('1', '1');
map.put('8', '8');
int l = 0, r = num.length() - 1;
while (l <= r) {
if (!map.containsKey(num.charAt(l))) return false;
if (map.get(num.charAt(l)) != num.charAt(r))
return false;
l++;
r--;
}
return true;
}
2)好炫酷,好省空间!直接hashmap没用,用了“00 11 88 696”这个字符串!
public boolean isStrobogrammatic(String num) {
for (int i=0, j=num.length()-1; i <= j; i++, j--)
if (!"00 11 88 696".contains(num.charAt(i) + "" + num.charAt(j)))
return false;
return true;
}
四、注意
1. 2和5不是180度等效的…
2. 别忘了0吖
五、问题
暂无