题目地址:Restore IP Addresses - LeetCode
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
这道题目是XX的面试时出的算法题。难度不大,当时我是打算用三个for循环来解决这个问题。结果面试官说你用三个for循环太土了,用递归吧。
然后我用递归写了一遍。递归写起来比直接For循环更长,代码也更不好看,花的时间也挺多的。事后想起来当时我应该怼回去的,坚持用3个for循环写。
Python解法如下:
class Solution:
def restoreIpAddresses(self, s: str):
result = []
length = len(s)
if length == 0:
return result
for i in range(1, 4):
if int(s[:i]) > 255 or(i > 1 and s[0] == '0'):
continue
for j in range(1, 4):
if i+j > length or int(s[i:i+j]) > 255 or(j > 1 and s[i] == '0'):
continue
for k in range(1, 4):
if i+j+k >= length or int(s[i+j:i+j+k]) > 255 \
or int(s[i+j+k:]) > 255 or (k > 1 and s[i+j] == '0') or(length-i-j-k > 1 and s[i+j+k] == '0'):
continue
result.append(s[:i]+'.'+s[i:i+j]+'.' +
s[i+j:i+j+k]+'.'+s[i+j+k:])
return result