从左到右遍历字符串,遍历的同时维护当前片段的开始位置start和结束位置end。初始时start = end = 0
对于每个访问到的字母a,得到当前字母的最后一次出现的下标位置
e
n
d
c
end_c
endc,则当前片段的结束下标一定不会小于
e
n
d
c
end_c
endc,因此令end = max(end, endc)
当访问到下标end时,当前片段访问结束,当前片段的下标范围时[start,end],长度为end - start + 1,将其添加到返回值中,然后令start = end + 1,继续寻找下一个片段
重复上述过程,知道遍历完字符串
AC代码
classSolution{public List<Integer>partitionLabels(String S){int[] last =newint[26];int len = S.length();for(int i =0; i < len; i++){
last[S.charAt(i)-'a']= i;}
List<Integer> ans =newArrayList<Integer>();int start =0;int end =0;for(int i =0; i < len; i++){
end = Math.max(end, last[S.charAt(i)-'a']);if(i == end){
ans.add(end - start +1);
start = end +1;}}return ans;}}
本地测试代码
package com.company;import java.util.ArrayList;import java.util.List;publicclassSolution_763{publicstatic List<Integer>partitionLabels(String S){int[] last =newint[26];int len = S.length();for(int i =0; i < len; i++){
last[S.charAt(i)-'a']= i;}
List<Integer> ans =newArrayList<Integer>();int start =0;int end =0;for(int i =0; i < len; i++){
end = Math.max(end, last[S.charAt(i)-'a']);if(i == end){
ans.add(end - start +1);
start = end +1;}}return ans;}publicstaticvoidmain(String[] args){
System.out.println(partitionLabels("ababcbacadefegdehijhklij"));}}
题目链接https://leetcode-cn.com/problems/partition-labels/解题思路由于同一个字母只能出现在同一个片段,显然同一个字母得第一次出现得下标位置和最后一次出现的下标位置必须出现在同一个片段。因此需要遍历字符串,得到每个字母最后一次出现的下标位置从左到右遍历字符串,遍历的同时维护当前片段的开始位置start和结束位置end。初始时start = end = 0对于每个访问到的字母a,得到当前字母的最后一次出现的下标位置endcend_cendc,则