Skip to content

Latest commit

 

History

History
59 lines (47 loc) · 1.37 KB

93.restore-IP-addresses.md

File metadata and controls

59 lines (47 loc) · 1.37 KB

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"]

JavaScript

/**
 * @param {string} s
 * @return {string[]}
 */
var restoreIpAddresses = function (s) {
    if (s.length < 4 || s.length > 12) {
        return [];
    }

    let result = [];

    IpAddresses(s, result, [], 1, 0);
    IpAddresses(s, result, [], 2, 0);
    IpAddresses(s, result, [], 3, 0);

    return result;
};

function IpAddresses(s, result, arrayLocalResult, count, iteration) {

    let startSubstring = arrayLocalResult.join('').length;
    let endSubsctring = startSubstring + count;
    if (endSubsctring > s.length) {
        return;
    }
    var newArray = arrayLocalResult.slice(0);
    var substring = s.substring(startSubstring, endSubsctring);
    if (+substring > 255 || substring.length !== ('' + +substring).length) {
        return;
    }
    newArray.push(substring);

    if (iteration === 3) {
        if (s.length === endSubsctring) {
            result.push(newArray.join('.'));
        }
        return;
    }
    IpAddresses(s, result, newArray, 1, iteration + 1);
    IpAddresses(s, result, newArray, 2, iteration + 1);
    IpAddresses(s, result, newArray, 3, iteration + 1);
}

restoreIpAddresses('25525511135');