• 一、题目
  • 二、解题思路
  • 三、解题代码

    一、题目

    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)

    给一个由数字组成的字符串。求出其可能恢复为的所有IP地址。

    注意 :中间IP位置不能以0开始,0.01.01.1非法,应该是0.0.101.1或者0.0.10.11

    二、解题思路

    方法一:

    直接三种循环暴力求解

    方法二:

    深度搜索,回溯

    三、解题代码

    方法一

    1. public class Solution {
    2. /**
    3. * @param s the IP string
    4. * @return All possible valid IP addresses
    5. */
    6. public ArrayList<String> restoreIpAddresses(String s) {
    7. ArrayList<String> res = new ArrayList<String>();
    8. int len = s.length();
    9. for(int i = 1; i<4 && i<len-2; i++){
    10. for(int j = i+1; j<i+4 && j<len-1; j++){
    11. for(int k = j+1; k<j+4 && k<len; k++){
    12. String s1 = s.substring(0,i), s2 = s.substring(i,j), s3 = s.substring(j,k), s4 = s.substring(k,len);
    13. if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4)){
    14. res.add(s1+"."+s2+"."+s3+"."+s4);
    15. }
    16. }
    17. }
    18. }
    19. return res;
    20. }
    21. public boolean isValid(String s){
    22. if(s.length()>3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s)>255)
    23. return false;
    24. return true;
    25. }
    26. }

    方法二

    1. public class Solution {
    2. /**
    3. * @param s the IP string
    4. * @return All possible valid IP addresses
    5. */
    6. public ArrayList<String> restoreIpAddresses(String s) {
    7. ArrayList<String> result = new ArrayList<String>();
    8. ArrayList<String> list = new ArrayList<String>();
    9. if(s.length() <4 || s.length() > 12)
    10. return result;
    11. helper(result, list, s , 0);
    12. return result;
    13. }
    14. public void helper(ArrayList<String> result, ArrayList<String> list, String s, int start){
    15. if(list.size() == 4){
    16. if(start != s.length())
    17. return;
    18. StringBuffer sb = new StringBuffer();
    19. for(String tmp: list){
    20. sb.append(tmp);
    21. sb.append(".");
    22. }
    23. sb.deleteCharAt(sb.length()-1);
    24. result.add(sb.toString());
    25. return;
    26. }
    27. for(int i=start; i<s.length() && i < start+3; i++){
    28. String tmp = s.substring(start, i+1);
    29. if(isvalid(tmp)){
    30. list.add(tmp);
    31. helper(result, list, s, i+1);
    32. list.remove(list.size()-1);
    33. }
    34. }
    35. }
    36. private boolean isvalid(String s){
    37. if(s.charAt(0) == '0')
    38. return s.equals("0"); // to eliminate cases like "00", "10"
    39. int digit = Integer.valueOf(s);
    40. return digit >= 0 && digit <= 255;
    41. }
    42. }