Skip to content

Commit

Permalink
添加 0383.赎金信.md Scala版本
Browse files Browse the repository at this point in the history
  • Loading branch information
wzqwtt committed May 13, 2022
1 parent 53379c0 commit 16c6abf
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion problems/0383.赎金信.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,68 @@ impl Solution {
}
}
```

Scala:

版本一: 使用数组作为哈希表
```scala
object Solution {
def canConstruct(ransomNote: String, magazine: String): Boolean = {
// 如果magazine的长度小于ransomNote的长度,必然是false
if (magazine.length < ransomNote.length) {
return false
}
// 定义一个数组,存储magazine字符出现的次数
val map: Array[Int] = new Array[Int](26)
// 遍历magazine字符串,对应的字符+=1
for (i <- magazine.indices) {
map(magazine(i) - 'a') += 1
}
// 遍历ransomNote
for (i <- ransomNote.indices) {
if (map(ransomNote(i) - 'a') > 0)
map(ransomNote(i) - 'a') -= 1
else return false
}
// 如果上面没有返回false,直接返回true,关键字return可以省略
true
}
}
```
版本二: 使用HashMap
```scala
object Solution {
import scala.collection.mutable
def canConstruct(ransomNote: String, magazine: String): Boolean = {
// 如果magazine的长度小于ransomNote的长度,必然是false
if (magazine.length < ransomNote.length) {
return false
}
// 定义map,key是字符,value是字符出现的次数
val map = new mutable.HashMap[Char, Int]()
// 遍历magazine,把所有的字符都记录到map里面
for (i <- magazine.indices) {
val tmpChar = magazine(i)
// 如果map包含该字符,那么对应的value++,否则添加该字符
if (map.contains(tmpChar)) {
map.put(tmpChar, map.get(tmpChar).get + 1)
} else {
map.put(tmpChar, 1)
}
}
// 遍历ransomNote
for (i <- ransomNote.indices) {
val tmpChar = ransomNote(i)
// 如果map包含并且该字符的value大于0,则匹配成功,map对应的--,否则直接返回false
if (map.contains(tmpChar) && map.get(tmpChar).get > 0) {
map.put(tmpChar, map.get(tmpChar).get - 1)
} else {
return false
}
}
// 如果上面没有返回false,直接返回true,关键字return可以省略
true
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit 16c6abf

Please sign in to comment.