Leetcode 93. Restore IP Addresses
Posted zhangwj0101
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 93. Restore IP Addresses相关的知识,希望对你有一定的参考价值。
Question
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)
Code
public List<String> restoreIpAddresses(String s)
if (s == null)
return null;
List<String> ret = new ArrayList<>();
List<String> path = new ArrayList<>();
dfs(s, 0, path, ret);
return ret;
public void dfs(String s, int index, List<String> path, List<String> ret)
if (path.size() == 4)
if (index == s.length())
StringBuilder sb = new StringBuilder();
for (String str : path)
sb.append(str);
sb.append('.');
sb.deleteCharAt(sb.length() - 1);
ret.add(sb.toString());
return;
int len = s.length();
for (int i = index; i < index + 3 && i < len; i++)
if (s.charAt(index) == '0' && i > index)
break;
String pre = s.substring(index, i + 1);
int num = Integer.parseInt(pre);
if (num > 255)
continue;
path.add(pre);
dfs(s, i + 1, path, ret);
path.remove(path.size() - 1);
以上是关于Leetcode 93. Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 93. Restore IP Addresses
[leetcode]93. Restore IP Addresses还原IP地址
LeetCode-93-Restore IP Addresses
LeetCode93. Restore IP Addresses 面试题