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)

Solution:

  1. public class Solution {
  2. public List<String> restoreIpAddresses(String s) {
  3. List<String> res = new ArrayList<String>();
  4. helper(s, 0, 0, "", res);
  5. return res;
  6. }
  7. void helper(String s, int index, int segment, String sol, List<String> res) {
  8. if (segment == 4 && index == s.length()) {
  9. res.add(sol);
  10. return;
  11. }
  12. // too many characters left
  13. if (s.length() > index + (4 - segment) * 3) {
  14. return;
  15. }
  16. // not enough characters left
  17. if (s.length() < index + (4 - segment)) {
  18. return;
  19. }
  20. for (int i = index; i < index + 3 && i < s.length(); i++) {
  21. String str = s.substring(index, i + 1);
  22. int num = Integer.parseInt(str);
  23. if ((s.charAt(index) == '0' && i > index) || (num > 255)) {
  24. return;
  25. }
  26. helper(s, i + 1, segment + 1, sol + str + (segment == 3 ? "" : "."), res);
  27. }
  28. }
  29. }