[Algorithom] Valid IP address

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
}

 

posted @   Zhentiw  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-12-08 [AWS] CloudFormation: create EC2 with SecurityGroupIds for custom VPC
2020-12-08 [Javascript] Broadcaster + Operator + Listener pattern -- 24. Design choice, ifElse or merge
2020-12-08 [Git] Revert to a old commit
2020-12-08 [Tools] Dendron
2019-12-08 [Algorithm] 46. Permutations
2019-12-08 [React] Write a generic React Suspense Resource factory
2019-12-08 [React] Fetch Data with React Suspense
点击右上角即可分享
微信分享提示