【发布时间】:2019-04-04 21:00:06
【问题描述】:
我正在解决LeetCode.com上的一个问题:
给出了一个由小写字母组成的字符串 S。我们希望将这个字符串分成尽可能多的部分,以便每个字母最多出现在一个部分中,并返回一个表示这些部分大小的整数列表。
示例:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
说明:
分区是“ababcbaca”、“defegde”、“hijhklij”。 这是一个分区,因此每个字母最多出现在一个部分中。 像“ababcbacadefegde”、“hijhklij”这样的分区是不正确的,因为它将 S 分成更少的部分。
public List<Integer> partitionLabels(String S) {
if(S == null || S.length() == 0){
return null;
}
List<Integer> list = new ArrayList<>();
int[] map = new int[26]; // record the last index of the each char
for(int i = 0; i < S.length(); i++){
map[S.charAt(i)-'a'] = i;
}
// record the end index of the current sub string
int last = 0;
int start = 0;
for(int i = 0; i < S.length(); i++){
last = Math.max(last, map[S.charAt(i)-'a']);
if(last == i){
list.add(last - start + 1);
start = last + 1;
}
}
return list;
}
}
虽然我确实了解解决方案,但我对声明 last = Math.max(last, map[S.charAt(i)-'a']); 和子句 if(last == i) 不太满意。这里到底在做什么?
【问题讨论】: