220 字 1 分钟阅读

给定一个只包含数字的字符串,用以表示一个 IP 地址,返回所有可能从 s 获得的 有效 IP 地址 。你可以按任何顺序返回答案。

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

例如:”0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、”192.168.1.312” 和 “192.168@1.1” 是 无效 IP 地址。

示例 1:

输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

示例 2:

输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

输入:s = "1111"
输出:["1.1.1.1"]

示例 4:

输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]

示例 5:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

  • 0 <= s.length <= 3000
  • s 仅由数字组成

思路

回溯解决

解法

class Solution {

    List<String> result = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s == null || s.length() == 0) {
            return result;
        }
        backtracking(s, 0, new StringBuilder(), 0);
        return result;
    }

    public void backtracking(String str, int start, StringBuilder builder, int count) {
        if (start == str.length() || count == 4) {
            if (start == str.length() && count == 4) {
                result.add(new StringBuilder(builder).deleteCharAt(builder.length() - 1).toString());
            }
            return;
        }

        for (int j = 1; j <= 3 && start + j <= str.length(); j++) {
            String cur = str.substring(start, start + j);
            if (isValid(cur)) {
                //拼接字符串
                builder.append(cur).append(".");
                //回溯
                backtracking(str, start + j, builder, count + 1);
                //回溯撤销选择
                builder.delete(builder.length() - j - 1, builder.length());
            }
        }
    }

    public boolean isValid(String str) {
        if (str.length() > 1 && str.charAt(0) == '0') {
            return false;
        }
        if (Integer.valueOf(str) > 255) {
            return false;
        }
        return true;
    }
}