边工作边刷题:70天一遍leetcode: day 75-2
Strobogrammatic Number I/II/III
要点:记题,注意轴对称和点对称的区别。这题就是几个固定digit之间的palindrome
I
https://repl.it/CqLu
II
https://repl.it/CivO (java)
https://repl.it/CqKC (python)
- 外循环中止条件:2个或3个字符都是循环一次,每层n-2,所以是n>1
- 00不考虑的情况是n>3,因为是从内向外循环,2或者3是最外一层
- python: string可以unpack为单一char,但是变量个数必须和len(string)一样
III
https://repl.it/CkFM/2 (python iterate all results,只能beat 19.05%,懒得看快的方法了 https://discuss.leetcode.com/topic/50073/python-46ms-96-77-without-generating-all-the-numbers)
- II中的recursion就是从最短开始build到某个长度,而题的目标就是找到在low和high长度之间]的所有。所以不用外层的loop,单一的recursion就够。递归的过程就是不断增加长度,所以中途检查是不是在low/high的长度范围,同时是不是value在范围内
- positive and negative conditions:
- no positive as you keep counting until all paths fail,
- negative: two conditions:
- if len(path)+2>high.size() (every round you add two chars) or
- == but >int(high)
- 落入[low,high]之间的都有机会++res,另外need to eliminate two ‘0’ at outmost layer (unlike II, to simplify, still can recurse into it and just don’t count it)
- 中止条件:(1) >high.size() (比low小为什么也return呢?)(2) 等于high.size()但值超过
- string表示的数比较不要慌,python简单搞定int()
# 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.
# Hide Company Tags Google
# Hide Tags Hash Table Math
# Hide Similar Problems (M) Strobogrammatic Number II (H) Strobogrammatic Number III
class Solution(object):
def isStrobogrammatic(self, num):
"""
:type num: str
:rtype: bool
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['1', '8', '0']
i,j = 0, len(num)-1
if len(num)>1 and num[0]=='0': return False
while i<=j:
if i==j:
return num[i] in mid
else:
if num[i] not in umap or umap[num[i]]!=num[j]:
return False
i+=1
j-=1
return True
import java.util.*;
class Main {
public static void main(String[] args) {
Solution sol = new Solution();
List<String> res = sol.findStrobogrammatic(5);
for(String s : res) {
System.out.println(s);
}
}
}
class Solution {
public List<String> findStrobogrammatic(int n) {
int[] nums = new int[]{1,8,6,9};
List<String> solutions = new ArrayList<>();
StringBuilder sb = new StringBuilder();
stroboHelper(nums, 0, n/2, sb, solutions);
// List<String> res = new ArrayList<>();
// for(String s : solutions) {
// }
return solutions;
}
void stroboHelper(int[] nums, int start, int n, StringBuilder sb, List<String> solutions) {
if(start==n) {
solutions.add(sb.toString());
return;
}
for(int i : nums) {
sb.append(Integer.toString(i));
stroboHelper(nums, start+1, n, sb, solutions);
sb.setLength(sb.length()-1);
}
}
}
# 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.
# For example,
# Given n = 2, return ["11","69","88","96"].
# Hint:
# Try to use recursion and notice that it should recurse with n - 2 instead of n - 1.
# Hide Company Tags Google
# Hide Tags Math Recursion
# Hide Similar Problems (E) Strobogrammatic Number (H) Strobogrammatic Number III
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['1', '8', '0']
def helper(n, res, solutions):
if n<=0:
if not n and (len(res)==1 or res[0]!='0'):
solutions.append(res)
return
for k in umap.keys():
helper(n-2, k+res+umap[k], solutions)
solutions = []
if n%2==1:
for i in mid:
helper(n-1, i, solutions)
else:
helper(n, "", solutions)
return solutions
sol = Solution()
assert sol.findStrobogrammatic(2)==["11","88","96","69"]
assert sol.findStrobogrammatic(1)==["1","8","0"]
# 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.
# Hide Tags Math Recursion
# Hide Similar Problems (E) Strobogrammatic Number (M) Strobogrammatic Number II
class Solution(object):
def strobogrammaticInRange(self, low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
umap = {'1':'1', '8':'8', '6':'9', '9':'6', '0':'0'}
mid = ['', '1', '8', '0']
self.count = 0
def helper(low, high, res):
l = len(res)
if len(low) <= l <= len(high):
if l==len(high) and int(res)>int(high): return
if int(res)>=int(low) and (l==1 or res[0]!='0'):
self.count+=1
#print res
if l+2 > len(high):
return
for k in umap.keys():
helper(low, high, k+res+umap[k])
solutions = []
for m in mid:
helper(low, high, m)
return self.count
sol = Solution()
assert sol.strobogrammaticInRange("50","100")==3
assert sol.strobogrammaticInRange("12","1200")==17
边工作边刷题:70天一遍leetcode: day 75-2的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 75
Group Shifted Strings 要点:开始就想到了string之间前后字符diff要相同. 思维混乱的地方:和某个string的diff之间是没有关系的.所以和单个string是否在那个点 ...
- 边工作边刷题:70天一遍leetcode: day 89
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
- 边工作边刷题:70天一遍leetcode: day 77
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
- 边工作边刷题:70天一遍leetcode: day 78
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
- 边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
- 边工作边刷题:70天一遍leetcode: day 101
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
- 边工作边刷题:70天一遍leetcode: day 1
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
- 边工作边刷题:70天一遍leetcode: day 70
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
- 边工作边刷题:70天一遍leetcode: day 71-3
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
- 边工作边刷题:70天一遍leetcode: day 71-2
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
随机推荐
- PHP KMP算法实现
function getNext( $str ){ $ret = array(0=>0); for( $j =1; $j < strlen($str); $j++ ){ $_s = sub ...
- Linux里如何查找文件内容
Linux查找文件内容的常用命令方法. 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符串" 文件名例子:在当前目录里第一级文件夹中寻找包含指定字符串的.in文件g ...
- 线上mysql内存持续增长直至内存溢出被killed分析(已解决)
来新公司前,领导就说了,线上生产环境Mysql库经常会发生日间内存爆掉被killed的情况,结果来到这第一天,第一件事就是要根据线上服务器配置优化配置,同时必须找出现在mysql内存持续增加爆掉的原因 ...
- JSON数据解析(转)
上篇随笔详细介绍了三种解析服务器端传过来的xml数据格式,而对于服务器端来说,返回给客户端的数据格式一般分为html.xml和json这三种格式,那么本篇随笔将讲解一下json这个知识点,包括如何通过 ...
- xscript脚本
最近看<游戏脚本高级编程>,然后顺便把里面实现的虚拟机,汇编器以及编译器手动用C++重写了一遍,原版书中提供的代码,风格不是很好,而且有几处BUG.我现在开源的代码中已经修复了BUG,而且 ...
- __proto__
proto 以前要访问原型, 必须使用构造函数来实现. 无法直接使用实例对象来访问原型. 火狐最早引入属性 __proto__ 表示使用实例对象引用原型. 但是早期是非标准的. 通过该属性可以允许使用 ...
- React对话框组件实现
当下前端届最火的技术之一莫过于React + Redux + webpack的技术结合.最近公司内部也正在转react,这周主要做了个React的modal组件,接下来谈下具体实现过程. 基本的HTM ...
- 2015第18本:从0到1,ZERO to ONE, Notes on startups, or how to build the future
<从0到1>中文版的副标题是”开创商业与未来的秘密“,题目大得吓人,英文副标题就谨慎了许多:Notes on startups, or how to build the future. 全 ...
- C迷途指针
在计算机编程领域中,迷途指针,或称悬空指针.野指针,指的是不指向任何合法的对象的指针. 当所指向的对象被释放或者收回,但是对该指针没有作任何的修改,以至于该指针仍旧指向已经回收的内存地址,此情况下该指 ...
- storyBoard配置错误导致崩溃 superview]: unrecognized selector...
控制台打印崩溃原因 [TaskStartVC superview]: unrecognized selector sent to instance RT TaskStartVC是一个同storyBoa ...