您的位置:首页 > 其它

LeetCode力扣之Restore IP Addresses

2018-03-13 16:53 295 查看
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)
package leetCode;

import java.util.ArrayList;
import java.util.List;

/**
* Created by lxw, liwei4939@126.com on 2018/3/13.
*/
public class L093_Restore_IP_Addresses {

public List<String> restoreIpAddresses(String s){
List<String> solutions = new ArrayList<>();
restoreIp(s, solutions, 0, "", 0);
return solutions;
}

private void restoreIp(String ip, List<String> solutions,
int idx, String restored, int count){

if (count > 4) return;
if (count == 4 && idx == ip.length()){
solutions.add(restored);
}
for (int i = 1; i < 4; i++){

if (idx + i >ip.length()){
break;
}

String str = ip.substring(idx, idx + i);
if ((str.startsWith("0") && str.length() > 1) ||
(i ==3 && Integer.parseInt(str) > 255)){
continue;
}

restoreIp(ip, solutions, idx+i, restored +str +(count == 3? "":"."), count+1);

}
}

public static void main(String[] args){
L093_Restore_IP_Addresses tmp = new L093_Restore_IP_Addresses();
String str = "25525511136";
System.out.println(tmp.restoreIpAddresses(str));
}

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