https://leetcode.com/problems/partition-labels/description/
题目大意:分割一个字符串,使得分割后的每段中出现的字母,仅在这段中出现。要求尽可能的多分几段。
解题思路:先从左往右扫一遍得到每个字母最先出现的位置,再从右往左扫一遍,得到每个字母最后出现的位置。之后贪心的分段即可。
class Solution {
public List<Integer> partitionLabels(String S) {
int n =S.length();
int[] pre = new int[26];
int[] las = new int[26];
Arrays.fill(pre,-1);
Arrays.fill(las,-1);
for(int i=0;i<n;i++)
{
char tmp = S.charAt(i);
if(pre[tmp-'a']==-1) pre[tmp-'a'] = i;
}
for(int i=n-1;i>=0;i--)
{
char tmp = S.charAt(i);
if(las[tmp-'a']==-1) las[tmp-'a'] = i;
}
List<Integer> res = new LinkedList<>();
for(int i=0;i<n;i++)
{
char tmp = S.charAt(i);
int end = las[tmp-'a'];
for(int j=i+1;j<end;j++)
{
end = Math.max(las[S.charAt(j)-'a'],end);
}
res.add(end - i +1);
i = end;
}
return res;
}
}