Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 037bebb

Browse files
committed
添加 剑指Offer05.替换空格.md Scala版本
1 parent f2dcdbe commit 037bebb

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

‎problems/剑指Offer05.替换空格.md‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,62 @@ func replaceSpace(_ s: String) -> String {
413413
}
414414
```
415415

416+
Scala:
416417

417-
418+
方式一: 双指针
419+
```scala
420+
object Solution {
421+
def replaceSpace(s: String): String = {
422+
var count = 0
423+
s.foreach(c => if (c == ' ') count += 1) // 统计空格的数量
424+
val sOldSize = s.length // 旧数组字符串长度
425+
val sNewSize = s.length + count * 2 // 新数组字符串长度
426+
val res = new Array[Char](sNewSize) // 新数组
427+
var index = sNewSize - 1 // 新数组索引
428+
// 逆序遍历
429+
for (i <- (0 until sOldSize).reverse) {
430+
if (s(i) == ' ') {
431+
res(index) = '0'
432+
index -= 1
433+
res(index) = '2'
434+
index -= 1
435+
res(index) = '%'
436+
} else {
437+
res(index) = s(i)
438+
}
439+
index -= 1
440+
}
441+
res.mkString
442+
}
443+
}
444+
```
445+
方式二: 使用一个集合,遇到空格就添加%20
446+
```scala
447+
object Solution {
448+
import scala.collection.mutable.ListBuffer
449+
def replaceSpace(s: String): String = {
450+
val res: ListBuffer[Char] = ListBuffer[Char]()
451+
for (i <- s.indices) {
452+
if (s(i) == ' ') {
453+
res += '%'
454+
res += '2'
455+
res += '0'
456+
}else{
457+
res += s(i)
458+
}
459+
}
460+
res.mkString
461+
}
462+
}
463+
```
464+
方式三: 使用map
465+
```scala
466+
object Solution {
467+
def replaceSpace(s: String): String = {
468+
s.map(c => if(c == ' ') "%20" else c).mkString
469+
}
470+
}
471+
```
418472

419473

420474
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /