ps | |
---|---|
링크 | leetcode.com/… |
출처 | LeetCode |
문제 번호 | 93 |
문제명 | Restore IP Addresses |
레벨 | Medium |
분류 |
완전탐색 |
시간복잡도 | O(1) |
사용한 언어 | Python |
제출기록 | 24 ms / 14.3 MB |
최고기록 | 16ms |
해결날짜 | 2020/11/26 |
"""Solution code for "LeetCode 93. Restore IP Addresses". (Non-recursive
version)
- Problem link: https://leetcode.com/problems/restore-ip-addresses/
- Solution link: http://www.teferi.net/ps/problems/leetcode/93
"""
import itertools
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
ip_list = []
for lengths in itertools.product([1, 2, 3], repeat=4):
if sum(lengths) != len(s):
continue
numbers = []
beg = 0
for l in lengths:
number = s[beg:beg + l]
if (number[0] == '0' and l > 1) or int(number) > 255:
break
numbers.append(number)
beg += l
else:
ip_list.append('.'.join(numbers))
return ip_list
"""Solution code for "LeetCode 93. Restore IP Addresses".
- Problem link: https://leetcode.com/problems/restore-ip-addresses/
- Solution link: http://www.teferi.net/ps/problems/leetcode/93
"""
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
def solveRec(numbers, s):
if len(numbers) == 4:
if not s:
ip_list.append('.'.join(numbers))
return
for l in range(1, 4):
if l > len(s):
break
number = s[:l]
if int(number) <= 255:
solveRec(numbers + [number], s[l:])
if s[0] == '0':
break
ip_list = []
solveRec([], s)
return ip_list