码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Restore IP Addresses

时间:2014-07-02 14:45:41      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   os   

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)

https://oj.leetcode.com/problems/restore-ip-addresses/

 

思路:要打印所有的结果,只能dfs枚举了。

bubuko.com,布布扣
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> restoreIpAddresses(String s) {
        List<String> res = new ArrayList<String>();
        if (s.length() > 12)
            return res;
        StringBuilder sb = new StringBuilder();
        dfs(res, sb, s, 0);
        return res;

    }

    private void dfs(List<String> res, StringBuilder sb, String s, int depth) {
        // System.out.println("sb:" + sb + ",s:" + s + ",depth:" + depth);
        if (depth > 4)
            return;
        if (depth == 4) {
            if (!s.equals(""))
                return;
            else {
                res.add(sb.toString().substring(0, sb.length() - 1));
            }

        }

        for (int i = 1; i <= s.length() && i <= 3; i++) {
            String toInsert = s.substring(0, i);
            if (isValid(toInsert)) {
                sb.append(toInsert + ".");
                dfs(res, sb, s.substring(i), depth + 1);
                sb.delete(sb.length() - i - 1, sb.length());
            }
        }

    }

    private boolean isValid(String toInsert) {
        int num = Integer.parseInt(toInsert);

        if (num > 255)
            return false;

        if (num != 0 && toInsert.startsWith("0") || num == 0 && !toInsert.equals("0"))
            return false;

        return true;
    }

    public static void main(String[] args) {
        String s = "010010";
        System.out.println(new Solution().restoreIpAddresses(s));
    }
}
View Code

 

[leetcode] Restore IP Addresses,布布扣,bubuko.com

[leetcode] Restore IP Addresses

标签:style   blog   http   java   color   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3819330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!