Skip to content

Commit a2b15fc

Browse files
committed
add scala solution for Permutation-In-String
1 parent 2c85f8d commit a2b15fc

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
//almost the same as Question 17 , we use exists instead of filter to find the first permutation
2+
object Solution {
3+
import scala.collection.mutable._
4+
5+
def checkInclusion(s1: String, s2: String): Boolean = {
6+
val diffMap = HashMap.empty[Char, Int]
7+
s1.foreach(updateMap(diffMap, _, 1))
8+
9+
(0 until s2.length).toList.exists(index => {
10+
if (index >= s1.length) updateMap(diffMap, s2(index - s1.length), 1)
11+
updateMap(diffMap, s2(index), -1)
12+
diffMap.isEmpty
13+
})
14+
}
15+
16+
def updateMap(map: HashMap[Char, Int], char: Char, incrementer: Int): Unit =
17+
map.get(char) match {
18+
case Some(number) if number + incrementer == 0 => map -= char
19+
case Some(number) => map += (char -> (number + incrementer))
20+
case None => map += (char -> incrementer)
21+
}
22+
}

0 commit comments

Comments
 (0)