forked from AlgoStudyGroup/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIs-Subsequence.kt
54 lines (51 loc) · 1.37 KB
/
Is-Subsequence.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class IsSubsequenceKotlin392 {
fun isSubsequence(s: String, t: String): Boolean {
if (s.isEmpty()) {
return true
}
var indexS = 0
t.forEach {
if (it == s[indexS]) {
if (++indexS == s.length) {
return true
}
}
}
return false
}
/*
fun isSubsequence(s: String, t: String): Boolean {
val tMap = mutableMapOf<Char, MutableList<Int>>()
t.forEachIndexed { index, c ->
tMap.computeIfAbsent(c) { mutableListOf() }.add(index)
}
var indexOft = 0
s.forEach {
indexOft = binarySearch(tMap[it], indexOft)
if (indexOft++ == -1) {
return false
}
}
return true
}
private fun binarySearch(nums: List<Int>?, target: Int): Int {
if (nums.isNullOrEmpty()) {
return -1
}
var left = 0
var right = nums.size - 1
while (left + 1 < right) {
val mid = left + (right - left) / 2
when {
nums[mid] <= target -> left = mid
nums[mid] > target -> right = mid
}
}
return when {
nums[left] >= target -> nums[left]
nums[right] >= target -> nums[right]
else -> -1
}
}
*/
}