From a8e4d4da767758488dbbc20564eab01a08e3e2dc Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 4 Jun 2022 22:04:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200093.=E5=A4=8D=E5=8E=9FIP?= =?UTF-8?q?=E5=9C=B0=E5=9D=80.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 6401824b..48bb6df2 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -659,6 +659,48 @@ func restoreIpAddresses(_ s: String) -> [String] { } ``` +## Scala + +```scala +object Solution { + import scala.collection.mutable + def restoreIpAddresses(s: String): List[String] = { + var result = mutable.ListBuffer[String]() + if (s.size < 4 || s.length > 12) return result.toList + var path = mutable.ListBuffer[String]() + + // 判断IP中的一个字段是否为正确的 + def isIP(sub: String): Boolean = { + if (sub.size > 1 && sub(0) == '0') return false + if (sub.toInt > 255) return false + true + } + + def backtracking(startIndex: Int): Unit = { + if (startIndex >= s.size) { + if (path.size == 4) { + result.append(path.mkString(".")) // mkString方法可以把集合里的数据以指定字符串拼接 + return + } + return + } + // subString + for (i <- startIndex until startIndex + 3 if i < s.size) { + var subString = s.substring(startIndex, i + 1) + if (isIP(subString)) { // 如果合法则进行下一轮 + path.append(subString) + backtracking(i + 1) + path = path.take(path.size - 1) + } + } + } + + backtracking(0) + result.toList + } +} +``` + -----------------------