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