A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).app
Write a function to determine if a number is strobogrammatic. The number is represented as a string.ide
For example, the numbers "69", "88", and "818" are all strobogrammatic.ui
时间 O(N) 空间 O(1)指针
翻转后对称的数就那么几个,咱们能够根据这个创建一个映射关系:8->8, 0->0, 1->1, 6->9, 9->6
,而后从两边向中间检查对应位置的两个字母是否有映射关系就好了。好比619,先判断6和9是有映射的,而后1和本身又是映射,因此是对称数。code
while循环的条件是left<=right
字符串
public class Solution { public boolean isStrobogrammatic(String num) { HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put('1','1'); map.put('0','0'); map.put('6','9'); map.put('9','6'); map.put('8','8'); int left = 0, right = num.length() - 1; while(left <= right){ // 若是字母不存在映射或映射不对,则返回假 if(!map.containsKey(num.charAt(right)) || num.charAt(left) != map.get(num.charAt(right))){ return false; } left++; right--; } return true; } }
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).get
Find all strobogrammatic numbers that are of length = n.string
For example, Given n = 2, return
["11","69","88","96"]
.it
时间 O(N) 空间 O(1)io
找出全部的可能,必然是深度优先搜索。可是每轮搜索如何创建临时的字符串呢?由于数是“对称”的,咱们插入一个字母就知道对应位置的另外一个字母是什么,因此咱们能够从中间插入来创建这个临时的字符串。这样每次从中间插入两个“对称”的字符,以前插入的就被挤到两边去了。这里有几个边界条件要考虑:
若是是第一个字符,即临时字符串为空时进行插入时,不能插入'0',由于没有0开头的数字
若是n=1的话,第一个字符则能够是'0'
若是只剩下一个带插入的字符,这时候不能插入'6'或'9',由于他们不能和本身产生映射,翻转后就不是本身了
这样,当深度优先搜索时遇到这些状况,则要相应的跳过
为了实现从中间插入,咱们用StringBuilder
在length/2的位置insert
就好了
public class Solution { char[] table = {'0', '1', '8', '6', '9'}; List<String> res; public List<String> findStrobogrammatic(int n) { res = new ArrayList<String>(); build(n, ""); return res; } public void build(int n, String tmp){ if(n == tmp.length()){ res.add(tmp); return; } boolean last = n - tmp.length() == 1; for(int i = 0; i < table.length; i++){ char c = table[i]; // 第一个字符不能为'0',但n=1除外。只插入一个字符时不能插入'6'和'9' if((n != 1 && tmp.length() == 0 && c == '0') || (last && (c == '6' || c == '9'))){ continue; } StringBuilder newTmp = new StringBuilder(tmp); // 插入字符c和它的对应字符 append(last, c, newTmp); build(n, newTmp.toString()); } } public void append(boolean last, char c, StringBuilder sb){ if(c == '6'){ sb.insert(sb.length()/2, "69"); } else if(c == '9'){ sb.insert(sb.length()/2, "96"); } else { sb.insert(sb.length()/2, last ? c : ""+c+c); } } }