Member-only story
Question from here: https://leetcode.com/problems/partition-labels/
Problem Statement
A string S
of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Constraints:
S
will have length in range[1, 500]
.S
will consist of lowercase letters ('a'
to'z'
) only.
How to approach this question
This question becomes less confusing when you realize three facts
- The constraint is actually a hint: s will only consist of lowercase letters
- Lowercase letters are of type char which means they have a codepoint. A codepoint is a numerical representation of a char, as defined by its UTF-8 encoding.
- There are 26 letters in the English alphabet
- You can add and subtract chars, which implicitly is adding and subtracting their codepoints