diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 7a702898..f361d1ef 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -676,5 +676,50 @@ impl Solution { } } ``` + + +## Scala + +```scala +object Solution { + + import scala.collection.mutable + + def partition(s: String): List[List[String]] = { + var result = mutable.ListBuffer[List[String]]() + var path = mutable.ListBuffer[String]() + + // 判断字符串是否回文 + def isPalindrome(start: Int, end: Int): Boolean = { + var (left, right) = (start, end) + while (left < right) { + if (s(left) != s(right)) return false + left += 1 + right -= 1 + } + true + } + + // 回溯算法 + def backtracking(startIndex: Int): Unit = { + if (startIndex >= s.size) { + result.append(path.toList) + return + } + // 添加循环守卫,如果当前分割是回文子串则进入回溯 + for (i <- startIndex until s.size if isPalindrome(startIndex, i)) { + path.append(s.substring(startIndex, i + 1)) + backtracking(i + 1) + path = path.take(path.size - 1) + } + } + + backtracking(0) + result.toList + } +} +``` + + -----------------------