编程面试题002——splitIp
2015-10-03 17:49
537 查看
题目描述
粗心的小G把IPV4地址的点分隔符去掉了,每个ip地址只剩下数字,请你帮他还原出所有可能的IP字符串。**
输入
**输入只有一行,内容为纯数字字符串。 如:25525511135
**
输出
**输出为多行。
每行一个点分隔的IPV4字符串。
多行以ASCII排序升序输出。
255.255.11.135
255.255.111.35
**
代码:
**public class Main { private static List<String> results = new ArrayList<String>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); convert2Address(input); for (String ip : results) { System.out.println(ip); } } public static void convert2Address(String input) { if (input == null && input.length() > 12) { return; } if (input.length() == 0) { return; } search(input, 0, ""); } public static void search(String input, int number, String address) { if (number == 3 && isValidIp(input)) { results.add(address + input); return; } for (int i = 0; i < 3 && i < input.length() - 1; i++) { String sub = input.substring(0, i + 1); if (isValidIp(sub)) search(input.substring(i + 1, input.length()), number + 1, address + sub + '.'); } } public static boolean isValidIp(String s) { if (s.charAt(0) == '0') return s.equals("0"); int num = Integer.parseInt(s); if (num <= 255 && num > 0) return true; else return false; } }
**