leetcode — restore-ip-addresses

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Source : https://oj.leetcode.com/problems/restore-ip-addresses/
 *
 *
 * * 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)
 */
public class RestoreIpAddress {

    public void recursion (String str, int index, int count, String ipStr, List<String> result) {
        if (index == str.length()) {
            if (count == 4) {
                result.add(ipStr.substring(0, ipStr.length()-1));
            }
            return;
        }

        // ip由四个数字组成
        if (count == 4) {
            return;
        }

        for (int i = index; i < str.length() && i < index + 3 ; i++) {
            // ip最大是255,如果是三位数第一位最大只能是2
            if (i - index > 1 && str.charAt(index) > '2') {
                return;
            }
            ipStr += str.substring(index, i+1) + ".";
            recursion(str, i+1, ++count, ipStr, result);
            ipStr = ipStr.substring(0, ipStr.length() - (i - index + 2));
            count --;
        }
    }

    public List<String> restore (String str) {
        if (str.length() < 4) {
            return Collections.EMPTY_LIST;
        }
        List<String> result = new ArrayList<String>();
        String ipStr = "";
        recursion(str, 0, 0, ipStr, result);
        return result;
    }


    public static void main(String[] args) {
        RestoreIpAddress restoreIpAddress = new RestoreIpAddress();
        List<String> list = restoreIpAddress.restore("25525511135");
        System.out.println(Arrays.toString(list.toArray(new String[list.size()])));

        list = restoreIpAddress.restore("11111");
        System.out.println(Arrays.toString(list.toArray(new String[list.size()])));

        list = restoreIpAddress.restore("19813713411");
        System.out.println(Arrays.toString(list.toArray(new String[list.size()])));

        list = restoreIpAddress.restore("");
        System.out.println(Arrays.toString(list.toArray(new String[list.size()])));
    }
}
posted @ 2017-11-05 19:30  lacker  阅读(169)  评论(0编辑  收藏  举报