[LeetCode]题解(python):093-Restore IP Addresses
2015-12-30 15:22
543 查看
[b]题目来源:[/b]
https://leetcode.com/problems/restore-ip-addresses/
[b]题意分析:[/b]
输入一个字符串,判断有多少种ip组合。比如,给定"25525511135",返回["255.255.11.135", "255.255.111.35"]
[b]题目思路:[/b]
要判断有多少种ip组合那么首先要知道,ip共有4个断,都是在0-255之间。那么题目可以理解成,在一个字符串里加入3个挡片,使得分成的4个子字符串的数值都小于255.这里可以用递归方法来做。solve(s,n)其中s是字符串,n是分成多少份。将s分别取1,2,3个字符,判断是否符合小于255,如果小于则判断solve(s[i:],n -1)是否满足的,如果有将s[:i]+solve(s[i:],n-1)。
[b]代码(Python):[/b]
View Code
转载请注明出处:/article/6365033.html
https://leetcode.com/problems/restore-ip-addresses/
[b]题意分析:[/b]
输入一个字符串,判断有多少种ip组合。比如,给定"25525511135",返回["255.255.11.135", "255.255.111.35"]
[b]题目思路:[/b]
要判断有多少种ip组合那么首先要知道,ip共有4个断,都是在0-255之间。那么题目可以理解成,在一个字符串里加入3个挡片,使得分成的4个子字符串的数值都小于255.这里可以用递归方法来做。solve(s,n)其中s是字符串,n是分成多少份。将s分别取1,2,3个字符,判断是否符合小于255,如果小于则判断solve(s[i:],n -1)是否满足的,如果有将s[:i]+solve(s[i:],n-1)。
[b]代码(Python):[/b]
class Solution(object): def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ def solve(s,n): if s == '': return [] if n == 1: if len(s) > 1 and s[0] == '0': return [] elif int(s) <= 255: return [s] else: return [] ans = [] if s[0] == '0': tmp = solve(s[1:],n-1) for i in tmp: ans.append('0.'+i) else: t = '' for i in range(3): if i < len(s): t += s[i] if int(t) <= 255: tmp = solve(s[i + 1:],n - 1) for j in tmp: ans.append(t + '.' +j) return ans return solve(s,4)
View Code
转载请注明出处:/article/6365033.html
相关文章推荐
- 域名解析正确性校验脚本(python多进程)
- Python爬虫学习笔记——豆瓣登陆(二)
- python 简易ss端口管理器
- [LeetCode]题解(python):092-Reverse Linked List II
- Python 文件I/O (转)
- [LeetCode]题解(python):091-Decode Ways
- SublimeText3 安装和配置,以及配置 Python 环境
- Python 功能和特点(新手必学)
- [LeetCode]题解(python):090-Subsets II
- python 安装pillow
- [LeetCode]题解(python):089-Gray Code
- python多线程
- python--文件处理范例
- [LeetCode]题解(python):088-Merge Sorted Array
- Python标准库10 多进程初步 (multiprocessing包)
- 笨方法学Python(11-15)
- Use Visual studio 2010 build Python2.7.10
- [LeetCode]题解(python):086-Partition List
- [LeetCode]题解(python):083-Remove Duplicates from Sorted List
- [LeetCode]题解(python):082-Remove Duplicates from Sorted List II