mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 0131.分割回文串.md Scala版本
This commit is contained in:
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user