首页 > 代码库 > 93. Restore IP Addresses
93. Restore IP Addresses
题目:
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)
链接: http://leetcode.com/problems/restore-ip-addresses/
6/4/2017
6ms, 31%
照着别人改的。注意的问题:
1. restore里面不需要2重循环,直接用i从pos到pos + 3就可以了
2. 第28-30行判断leading 0的方法不错
1 public class Solution { 2 public List<String> restoreIpAddresses(String s) { 3 List<String> ret = new ArrayList<>(); 4 List<String> list = new ArrayList<>(); 5 restore(s, ret, 0, list); 6 return ret; 7 } 8 private void restore(String s, List<String> ret, int index, List<String> list) { 9 if (list.size() == 4) { 10 if (index == s.length()) { 11 ret.add(new String(String.join(".", list))); 12 } 13 return; 14 } 15 for (int i = index; i < s.length() && i <= index + 3; i++) { 16 String tmp = s.substring(index, i + 1); 17 if (isValid(tmp)) { 18 list.add(tmp); 19 restore(s, ret, i + 1, list); 20 list.remove(list.size() - 1); 21 } 22 } 23 } 24 private boolean isValid(String s) { 25 if (s == null || s.length() == 0) { 26 return false; 27 } 28 if (s.charAt(0) == ‘0‘) { 29 return s.length() == 1; 30 } 31 int num = Integer.parseInt(s); 32 if (num < 0 || num >= 256) { 33 return false; 34 } 35 return true; 36 } 37 }
别人的答案:
三重循环
https://discuss.leetcode.com/topic/3919/my-code-in-java
更多讨论
https://discuss.leetcode.com/category/101/restore-ip-addresses
93. Restore IP Addresses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。