function validIPAddresses(string) {
const res= []
for (let i = 1; i < Math.min(string.length, 4); i++) {
const parts = ['', '', '', '']
parts[0] = string.slice(0, i)
if (!isPossible(parts[0])) {
continue
}
for (let j = i + 1; j < i + Math.min(string.length - i, 4); j++) {
parts[1] = string.slice(i, j)
if (!isPossible(parts[1])) {
continue
}
for (let k = j + 1; k < j + Math.min(string.length - j, 4); k++) {
parts[2] = string.slice(j, k)
parts[3] = string.slice(k)
if (isPossible(parts[2]) && isPossible(parts[3])) {
res.push(parts.join('.'))
}
}
}
}
return res;
}
function isPossible(str) {
const val = parseInt(str, 10)
if (val > 255) {
return false
}
return str.length === val.toString().length
}
标签:Algorithom,slice,string,IP,parts,length,Valid,isPossible,Math From: https://www.cnblogs.com/Answer1215/p/16965032.html