A string S
of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts
Note:
-
S
will have length in range[1, 500]
. -
S
will consist of lowercase letters ('a'
to'z'
) only
题意
给你一个串, 要求分割尽量多份,使得每份中的字母只在该被分割部分出现
思路
扫一遍串,用一个map存每个字母的最大index值
扫一遍串,lock住start指针,更新即将被分割子串最大的last值,当last == i, 则找到一个被分割子串。
代码
1 class Solution { 2 public List<Integer> partitionLabels(String S) { 3 if(S == null || S.length() == 0){return null; } 4 List<Integer> list = new ArrayList<>(); 5 int[] map = new int[26]; 6 7 for(int i = 0; i < S.length(); i++){ 8 map[S.charAt(i)-'a'] = i; 9 } 10 11 int last = 0; 12 int start = 0; 13 for(int i = 0; i < S.length(); i++){ 14 last = Math.max(last, map[S.charAt(i)-'a']); 15 if(last == i){ 16 list.add(last - start + 1); 17 start = last + 1; 18 } 19 } 20 return list; 21 } 22 }