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 92ca3d5

Browse files
author
konstantin
committed
Easy942 challenge
1 parent c281a35 commit 92ca3d5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎src/easy/942. DI String Match .kt‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package easy
2+
3+
import ArraysTopic
4+
import GreedyTopic
5+
import MathTopic
6+
import StringTopic
7+
import TwoPointersTopic
8+
9+
/**
10+
* 942. DI String Match
11+
* https://leetcode.com/problems/length-of-last-word/
12+
*
13+
* Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
14+
* A word is a maximal substring consisting of non-space characters only.
15+
*/
16+
17+
class Easy942 : ArraysTopic, TwoPointersTopic, StringTopic, GreedyTopic, MathTopic {
18+
19+
fun diStringMatch(s: String): IntArray {
20+
val result = IntArray(s.length + 1)
21+
var top = 0
22+
var bottom = 0
23+
for (i in result.lastIndex - 1 downTo 0) {
24+
if (s[i] == 'I') {
25+
bottom--
26+
result[i] = bottom
27+
} else {
28+
top++
29+
result[i] = top
30+
}
31+
}
32+
return result.also { for (i in it.indices) it[i] -= bottom }
33+
}
34+
}
35+
36+
fun main() {
37+
println(Easy942().diStringMatch("IDID").toList())
38+
println(Easy942().diStringMatch("III").toList())
39+
println(Easy942().diStringMatch("DDI").toList())
40+
}

0 commit comments

Comments
(0)

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