Restore IP Addresses

https://leetcode.com/problems/restore-ip-addresses/
给定一个字符串,求能组成的所有的ip段

  • java
    DFS
public List restoreIpAddresses(String s) {
        List out = new ArrayList();
        List> res = new ArrayList>();
        restoreIpAddresses2Helper(s, out, res);
        List ll = new ArrayList();


        for (List info : res) {
            String[] tmp = info.toArray(new String[info.size()]);
            ll.add(String.join(".", tmp));
        }
        return ll;
    }

    public void restoreIpAddresses2Helper(String s, List out, List> res) {
        if (out.size() == 4) {
            if (s.equals("")) {
                res.add(new ArrayList(out));
            }
            return;
        }

        for (int i = 1; i <= Math.min(3, s.length()); i++) {
            String tmp = s.substring(0, i);

            // 0开头的两位、三位数字不要了
            if (i > 1 && s.startsWith("0")) {
                break;
            }

            // 大于255 不要了
            if (Integer.valueOf(tmp) > 255) {
                break;
            }
            out.add(tmp);
            restoreIpAddresses2Helper(s.substring(i), out, res);
            out.remove(out.size() - 1);
        }
    }

你可能感兴趣的:(Restore IP Addresses)