93. 复原 IP 地址【中等题】

题目链接

function restoreIpAddresses(s: string): string[] {
    const result: string[] = [];
    const backTrackIp = (s: string, startIndex: number, curNodes: string[]) => {
        if(curNodes.length > 4) {
            return;
        }
        if(s.length <= startIndex && curNodes.length === 4) {
            const newIp = curNodes.join('.');
            result.push(newIp);
            return;
        }
        for(let i = startIndex+1; i <= s.length; i++) {
            const newSection = s.slice(startIndex, i);
            if(newSection[0] === '0' && newSection.length>1) {
                return;
            }
            if(Number(newSection) > 255 ||Number(newSection)<0) {
                return;
            }
            curNodes.push(newSection);
            backTrackIp(s, i, curNodes);
            curNodes.pop();
        }
    };
    backTrackIp(s, 0, []);
    return result;
};

console.log(restoreIpAddresses("25525511135"));
console.log(restoreIpAddresses("0000"));
console.log(restoreIpAddresses("101023"));

results matching ""

    No results matching ""