添加 1047.删除字符串中的所有相邻重复项.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-16 17:24:47 +08:00
parent 61f5d920d0
commit 98bdccbe16

View File

@ -374,6 +374,27 @@ func removeDuplicates(_ s: String) -> String {
return String(stack) return String(stack)
} }
``` ```
Scala:
```scala
object Solution {
import scala.collection.mutable
def removeDuplicates(s: String): String = {
var stack = mutable.Stack[Int]()
var str = "" // 保存最终结果
for (i <- s.indices) {
var tmp = s(i)
// 如果栈非空并且栈顶元素等于当前字符,那么删掉栈顶和字符串最后一个元素
if (!stack.isEmpty && tmp == stack.head) {
str = str.take(str.length - 1)
stack.pop()
} else {
stack.push(tmp)
str += tmp
}
}
str
}
}
```
----------------------- -----------------------
<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>