Skip to content

Commit

Permalink
添加 剑指Offer05.替换空格.md Scala版本
Browse files Browse the repository at this point in the history
  • Loading branch information
wzqwtt committed May 14, 2022
1 parent f2dcdbe commit 037bebb
Showing 1 changed file with 55 additions and 1 deletion.
56 changes: 55 additions & 1 deletion problems/剑指Offer05.替换空格.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,62 @@ func replaceSpace(_ s: String) -> String {
}
```

Scala:


方式一: 双指针
```scala
object Solution {
def replaceSpace(s: String): String = {
var count = 0
s.foreach(c => if (c == ' ') count += 1) // 统计空格的数量
val sOldSize = s.length // 旧数组字符串长度
val sNewSize = s.length + count * 2 // 新数组字符串长度
val res = new Array[Char](sNewSize) // 新数组
var index = sNewSize - 1 // 新数组索引
// 逆序遍历
for (i <- (0 until sOldSize).reverse) {
if (s(i) == ' ') {
res(index) = '0'
index -= 1
res(index) = '2'
index -= 1
res(index) = '%'
} else {
res(index) = s(i)
}
index -= 1
}
res.mkString
}
}
```
方式二: 使用一个集合,遇到空格就添加%20
```scala
object Solution {
import scala.collection.mutable.ListBuffer
def replaceSpace(s: String): String = {
val res: ListBuffer[Char] = ListBuffer[Char]()
for (i <- s.indices) {
if (s(i) == ' ') {
res += '%'
res += '2'
res += '0'
}else{
res += s(i)
}
}
res.mkString
}
}
```
方式三: 使用map
```scala
object Solution {
def replaceSpace(s: String): String = {
s.map(c => if(c == ' ') "%20" else c).mkString
}
}
```


-----------------------
Expand Down

0 comments on commit 037bebb

Please sign in to comment.