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.
Note:
S will have length in range [1, 500].
S will consist of lowercase letters ('a' to 'z') only.
这题要求最多的partition。
那么我们从左到右遍历一遍,用贪心算法。
能分马上分。除非这个字母在后边还出现而不可分离。
那么聪明的读者可能想到了,我怎么知道这个/些字符在后边还有没有,有的话在多后?
我这里采用的是先扫一遍用HashMap把每个char的起始坐标给缓存起来,
第二遍直接查缓存,进而得出结果。
时间复杂度就是O(n)
No comments:
Post a Comment