forked from LeetCode-in-Racket/LeetCode-in-Racket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rkt
36 lines (33 loc) · 1.32 KB
/
Solution.rkt
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
; #Medium #String #Hash_Table #Greedy #Two_Pointers #Data_Structure_II_Day_7_String
; #Big_O_Time_O(n)_Space_O(1) #2025_02_12_Time_0_ms_(100.00%)_Space_101.55_MB_(100.00%)
(define/contract (partition-labels s)
(-> string? (listof exact-integer?))
(let* ([chars (string->list s)]
[position (make-vector 26 0)])
; First pass: record last position of each character
(for ([c chars]
[i (in-range (string-length s))])
(vector-set! position
(- (char->integer c) (char->integer #\a))
i))
; Second pass: find partitions
(let loop ([i 0]
[prev -1]
[max-pos 0]
[result '()])
(if (>= i (string-length s))
(reverse result)
(let* ([curr-char (string-ref s i)]
[curr-last-pos (vector-ref position
(- (char->integer curr-char)
(char->integer #\a)))]
[new-max (max max-pos curr-last-pos)])
(if (= i new-max)
(loop (add1 i)
i
new-max
(cons (- i prev) result))
(loop (add1 i)
prev
new-max
result)))))))