https://leetcode.cn/problems/partition-labels/
题目要求
给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。注意,划分结果需要满足:将所有划分结果按顺序连接,得到的字符串仍然是 s 。返回一个表示每个字符串片段的长度的列表。
hashmap存储字母下标
public List<Integer> partitionLabels(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int n = s.length();
for (int i = 0; i < n; i++) {
map.put(s.charAt(i), i);
}
List<Integer> res = new ArrayList<>();
int preRange = -1, curRange = 0;
for (int i = 0; i < n; i++) {
curRange = Math.max(curRange, map.get(s.charAt(i)));
if (i == curRange) {
res.add(curRange - preRange);
preRange = curRange;
}
}
return res;
}
数组存储下标
class Solution {
public List<Integer> partitionLabels(String s) {
int[] word = new int[26];
int n = s.length();
for (int i = 0; i < n; i++) {
word[s.charAt(i) - 'a'] = i;
}
List<Integer> res = new ArrayList<>();
int preRange = -1, curRange = 0;
for (int i = 0; i < n; i++) {
curRange = Math.max(curRange, word[s.charAt(i) - 'a']);
if (i == curRange) {
res.add(curRange - preRange);
preRange = curRange;
}
}
return res;
}
}
- 使用数组来存储下标可以提高执行时间;