【LeetCode】93. Restore IP Addresses

原题

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

难度:中等

题意解析:插入三个点分割输入的字符串,使其符合IP地址格式,需要返回所有符合要求的被分割后的字符串。

解法:这道题有两种解法

1) 三个for循环枚举点号位置     

 2) 回溯法遍历点号位置并剪枝    ✔

public static List restoreIpAddresses(String s) {
        List result = new ArrayList<>();
        int[] splitPosition = new int[5];
        splitPosition[4] = s.length();
        back(s, splitPosition, 0, result);
        return result;
    }

    public static void back(String s, int[] splitPosition, int numOfJoin, List result)
    {
        if(numOfJoin == 3)
        {
            if(splitPosition[3] >= s.length()) return;
            if(s.length() - splitPosition[3] > 3) return;
            String ip = "";
            for(int i = 0; i < 4; i++)
            {
                String temp = s.substring(splitPosition[i], splitPosition[i+1]);
                if(temp.length() > 1 && temp.startsWith("0")) return;
                int tempNum = Integer.parseInt(temp);
                if(tempNum < 0 || tempNum > 255) return;
                ip += i == 3 ? temp : temp + ".";
            }

            result.add(ip);
            return;
        }

        for(int i = 1; i <= 3; i++)
        {
            splitPosition[numOfJoin + 1] = splitPosition[numOfJoin] + i;
            back(s, splitPosition,numOfJoin+1, result);
            splitPosition[numOfJoin + 1] = 0;
        }
    }

 

你可能感兴趣的:(LeetCode,算法)