标签:leetcode string dfs 递归 java
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)
使用DFS的思想。结束条件是:ip地址是4部分。具体思路:ip地址每一部分最多有3位。先取出字符串s的第一位,判断是否符合要求。然后递归求解剩下的。取出前两位、取出前三位,进行类似的操作。符合要求的条件是 0-255,当有两位以上的时候,第一位不能为0。public void getString(String s,int num, List<String> subList, List<String> list) { if (num == 4 && s.equals("")) { String ip = ""; for (String str : subList) { ip = ip + str + "."; } list.add(ip.substring(0,ip.length() - 1)); } if (num < 4) { int len = s.length(); for (int i = 1; i < Math.min(4, len + 1); i++) { String str = s.substring(0, i); if (str.length() == 1 || (str.length() > 1 && str.charAt(0) != '0')){ int temp = Integer.parseInt(str); if (temp < 256) { subList.add(str); getString(s.substring(i, len), num + 1, subList, list); subList.remove(subList.size() - 1); } } } } } public List<String> restoreIpAddresses(String s) { List<String> list = new ArrayList<String>(); List<String> subList = new ArrayList<String>(); getString(s, 0, subList, list); return list; }
Restore IP Addresses,布布扣,bubuko.com
标签:leetcode string dfs 递归 java
原文地址:http://blog.csdn.net/u010378705/article/details/28889697