From e5bc6a0447dd6d613f5df96f1d002fa5a67792e1 Mon Sep 17 00:00:00 2001 From: solairerove Date: Mon, 6 Nov 2023 19:26:41 +0800 Subject: [PATCH] feature: partition labels --- arrays/ContainerWithMostWater.py | 1 + arrays/PartitionLabels.py | 16 ++++++++++++++++ arrays/test/test_partition_labels.py | 15 +++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 arrays/PartitionLabels.py create mode 100644 arrays/test/test_partition_labels.py diff --git a/arrays/ContainerWithMostWater.py b/arrays/ContainerWithMostWater.py index e801b08..7d2b146 100644 --- a/arrays/ContainerWithMostWater.py +++ b/arrays/ContainerWithMostWater.py @@ -1,5 +1,6 @@ from typing import List +# TODO: two pointers # O(n) time || O(1) space def max_area(self, height: List[int]) -> int: diff --git a/arrays/PartitionLabels.py b/arrays/PartitionLabels.py new file mode 100644 index 0000000..175c66e --- /dev/null +++ b/arrays/PartitionLabels.py @@ -0,0 +1,16 @@ +from typing import List + + +# O(n) time || O(n) space +def partition_labels(self, s: str) -> List[int]: + last_occurrence = {c: i for i, c in enumerate(s)} + res = [] + low = high = 0 + for i, c in enumerate(s): + high = max(high, last_occurrence[c]) + + if i == high: + res.append(high - low + 1) + low = high + 1 + + return res diff --git a/arrays/test/test_partition_labels.py b/arrays/test/test_partition_labels.py new file mode 100644 index 0000000..cbf56cb --- /dev/null +++ b/arrays/test/test_partition_labels.py @@ -0,0 +1,15 @@ +import unittest + +from arrays.PartitionLabels import partition_labels + + +class MyTestCase(unittest.TestCase): + def test_partition_labels(self): + self.assertEqual([9, 7, 8], partition_labels(self, s="ababcbacadefegdehijhklij")) + + def test_partition_labels_1(self): + self.assertEqual([10], partition_labels(self, s="eccbbbbdec")) + + +if __name__ == '__main__': + unittest.main()