You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
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.
Example 2:
Input: s = “eccbbbbdec”
Output: [10]
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
给出一个字符串s,把它分成尽可能多的部分,每个字母不能在多个部分出现(只能出现在其中一部分里)。
思路:
参考这篇题解
先用一个HashMap记录下每个字母出现的最远的位置,
因为字母只有26个,所以直接用数组代替HashMap。
比如example1, a出现的最远位置是8,
“ababcbaca defegdehijhklij”
就像这样遍历一遍数组,记录下每个字母最远的位置。
然后再遍历一遍,记录max位置,也就是到当前字母为止的最远位置,
如果到目前为止,所有字母都在max范围内,说明这一部分包含了这些字母,后面不会再出现这些字母了,
到何时为止截断一部分呢?就是max==i的时候,i是遍历的下标。因为超出了i,又要判断新的max了。
结果要返回的是每部分的长度,既然是长度,就需要用当前下标 - 该部分前面一个位置的下标。
所以再用一个变量pre记录前面元素的下标,当i = 0时,pre = -1。
max == i时截断一部分,pre=i。
public List<Integer> partitionLabels(String s) {
int n = s.length();
int[] idxs = new int[26];
int pre = -1;
List<Integer> result = new ArrayList<>();
int maxId = 0;
for(int i = 0; i < n; i ++) {
idxs[s.charAt(i) - 'a'] = i;
}
for(int i = 0; i < n; i ++) {
maxId = Math.max(maxId, idxs[s.charAt(i) - 'a']);
if(maxId == i) {
result.add(maxId - pre);
pre = i;
}
}
return result;
}
该博客介绍了如何将一个字符串按照每个字母只出现在一个部分的要求进行拆分,通过遍历字符串两次,记录每个字母的最远位置,并找到当前遍历位置的最大最远位置,当最大最远位置等于当前位置时,截取一部分。最终返回各部分的长度。
1151

被折叠的 条评论
为什么被折叠?



