您的位置:首页 > 编程语言 > Java开发

93. Restore IP Addresses | Java最短代码实现

2016-03-22 15:53 525 查看
原题链接:93. Restore IP Addresses
【思路】

本题考察回溯算法。本解法采用回溯算法,将ip分为4个字段,需要注意下面几点:

1. 每个字段的值均不超过255,且不以0为开头(单独的0允许)。否则,剪枝。

2. 如果4个字段都加入到temp中之后,四个字段长度之和不等于s.length() - 1,那么不可加入到result中。

public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
dfs(result, s, "", 0, "", 0);
return result;
}
private void dfs(List<String> result, String s, String temp, int curIndex, String curSum, int times) {
if (times < 4 && times > 0) {
temp = temp + curSum + '.';
curSum = "";
} else if (times == 4 && curIndex == s.length()) {  //得到4个字段过后,如果curIndex不小于s.length(),那么ip合法
result.add(temp + curSum);
}
for (int i = curIndex; i < s.length() && times < 4; i++) {
curSum = curSum + s.charAt(i);
if (curSum.length() > 1 && curSum.startsWith("0") || Integer.parseInt(curSum) > 255) //该字段ip不合法,剪枝
break;
dfs(result, s, temp, i + 1, curSum, times + 1);
}
}
147 / 147 test
cases passed. Runtime: 4
ms Your runtime beats 55.34% of javasubmissions.

欢迎优化!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: