题目描述
给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。
注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。
返回一个表示每个字符串片段的长度的列表。
示例 1:
输入:s = “ababcbacadefegdehijhklij”
输出:[9,7,8]
解释:
划分结果为 “ababcbaca”、“defegde”、“hijhklij” 。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 这样的划分是错误的,因为划分的片段数较少。
示例 2:
输入:s = “eccbbbbdec”
输出:[10]
提示:
1 <= s.length <= 500
s 仅由小写英文字母组成
代码
class Solution {
public List<Integer> partitionLabels(String s) {
List<Integer> result = new ArrayList<>();
HashMap<Character, Integer> hashMap = new HashMap<>();
//把每个字母在字符串中最后一个位置给记录下来,方便后面找最长的位置
for (int i = s.length() - 1; i >= 0; i--) {
if (hashMap.get(s.charAt(i)) == null) {
hashMap.put(s.charAt(i), i);
}
}
for (int i = 0; i < s.length(); i++) {
int index = hashMap.get(s.charAt(i));//直接找到当前字母的最后一个位置,最短也会从index这里划分
for (int j = i; j <= index; j++) {
//遍历这个子字符串的过程中如果发现只能再更后面划分就及时更新index
if (hashMap.get(s.charAt(j)) > index) {
index = hashMap.get(s.charAt(j));
}
}
result.add(index - i + 1);//将每个子字符串的长度记录在结果中
i = index;
}
return result;
}
}