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 16c6abf

Browse files
committed
添加 0383.赎金信.md Scala版本
1 parent 53379c0 commit 16c6abf

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

‎problems/0383.赎金信.md‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,68 @@ impl Solution {
360360
}
361361
}
362362
```
363-
363+
Scala:
364+
365+
版本一: 使用数组作为哈希表
366+
```scala
367+
object Solution {
368+
def canConstruct(ransomNote: String, magazine: String): Boolean = {
369+
// 如果magazine的长度小于ransomNote的长度,必然是false
370+
if (magazine.length < ransomNote.length) {
371+
return false
372+
}
373+
// 定义一个数组,存储magazine字符出现的次数
374+
val map: Array[Int] = new Array[Int](26)
375+
// 遍历magazine字符串,对应的字符+=1
376+
for (i <- magazine.indices) {
377+
map(magazine(i) - 'a') += 1
378+
}
379+
// 遍历ransomNote
380+
for (i <- ransomNote.indices) {
381+
if (map(ransomNote(i) - 'a') > 0)
382+
map(ransomNote(i) - 'a') -= 1
383+
else return false
384+
}
385+
// 如果上面没有返回false,直接返回true,关键字return可以省略
386+
true
387+
}
388+
}
389+
```
390+
版本二: 使用HashMap
391+
```scala
392+
object Solution {
393+
import scala.collection.mutable
394+
def canConstruct(ransomNote: String, magazine: String): Boolean = {
395+
// 如果magazine的长度小于ransomNote的长度,必然是false
396+
if (magazine.length < ransomNote.length) {
397+
return false
398+
}
399+
// 定义map,key是字符,value是字符出现的次数
400+
val map = new mutable.HashMap[Char, Int]()
401+
// 遍历magazine,把所有的字符都记录到map里面
402+
for (i <- magazine.indices) {
403+
val tmpChar = magazine(i)
404+
// 如果map包含该字符,那么对应的value++,否则添加该字符
405+
if (map.contains(tmpChar)) {
406+
map.put(tmpChar, map.get(tmpChar).get + 1)
407+
} else {
408+
map.put(tmpChar, 1)
409+
}
410+
}
411+
// 遍历ransomNote
412+
for (i <- ransomNote.indices) {
413+
val tmpChar = ransomNote(i)
414+
// 如果map包含并且该字符的value大于0,则匹配成功,map对应的--,否则直接返回false
415+
if (map.contains(tmpChar) && map.get(tmpChar).get > 0) {
416+
map.put(tmpChar, map.get(tmpChar).get - 1)
417+
} else {
418+
return false
419+
}
420+
}
421+
// 如果上面没有返回false,直接返回true,关键字return可以省略
422+
true
423+
}
424+
}
425+
```
364426
-----------------------
365427
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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