leetcode刷题笔记九十三题 复原IP地址

leetcode刷题笔记九十三题 复原IP地址

源地址:93. 复原IP地址

问题描述:

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。

示例:

输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

/**
本题使用的是回溯算法 + 剪枝去重思想
回溯条件:begin == length && splitTimes == 4,即成功分割四次且到达字符串末尾
剪枝条件比较多且杂:
1.当length < 4 || length > 12 不能构成IP地址
2.当length - begin < 4 - splitTimes || length - begin > 3 * (4 - splitTimes) 剩余部分不能构成IP地址
3.使用isIpAddress判断地址码是否有效,这里主要判断两种情况,是否有0开头或者结果大于255
*/
import scala.collection.mutable
object Solution {
    def restoreIpAddresses(s: String): List[String] = {
        val length = s.length
        if (length < 4 || length > 12) return List()
        var path = new mutable.ListBuffer[Int]()
        var res = new mutable.ListBuffer[String]()
        var begin = 0
        var splitTimes = 0

        def isIpAddress(s: String, left: Int, right: Int): Int = {
            val length = right - left + 1
            if (length > 1 && s(left) == '0') return -1
            var res = 0
            for(i <- left to right) res = res*10 + (s(i) - '0')
            if (res > 255) return -1
            return res
        }

        def dfs(s: String, length: Int, splitTimes: Int, begin: Int): Unit = {
            if (begin == length && splitTimes == 4) res += path.mkString(".").toString
            if (length - begin < 4 - splitTimes || length - begin > 3 * (4 - splitTimes)) return
            for (i <- 0 to 2 if begin + i < length){
                val ipAddress = isIpAddress(s, begin, begin+i)
                if (ipAddress != -1){
                    path += ipAddress
                    dfs(s, length, splitTimes+1, begin+i+1)
                    path = path.dropRight(1)
                }
            }
        }
        dfs(s, length, splitTimes, begin)
        return res.toList
    }
}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/13405716.html