https://oj.leetcode.com/problems/restore-ip-addresses/
http://blog.csdn.net/linhuanmars/article/details/24683699
public class Solution { public List<String> restoreIpAddresses(String s) { if (s == null || s.length() < 4) return Collections.emptyList(); // invalid input. List<String> result = new ArrayList<>(); help(s, 0, 0, result); return result; } private void help(String s, int dotnum, int start, List<String> result) { if (start > s.length() - 1) return; if (dotnum == 3) { if (isvalid(s, start, s.length() - 1)) { result.add(s); } return; } // Add one more dot. for (int i = start ; i < s.length() && i < start + 3 ; i ++) { if (isvalid(s, start, i)) { String ns = s.substring(0, i + 1) + "." + s.substring(i + 1, s.length()); help(ns, dotnum + 1, i + 2, result); } } } private boolean isvalid(String s, int start, int end) { int len = end - start + 1; if (len <= 0 || len > 3) return false; if (s.charAt(start) == ‘0‘ && len > 1) return false; Integer i = Integer.parseInt(s.substring(start, end + 1)); return i >= 0 && i <= 255; } }
[LeetCode]93 Restore IP Addresses
原文地址:http://7371901.blog.51cto.com/7361901/1599353