【LeetCode】 763. Partition Labels 划分字母区间(Medium)(JAVA)
题目地址: https://leetcode.com/problems/partition-labels/
题目描述:
A string S of lowercase English 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 English letters (‘a’ to ‘z’) only.
题目大意
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
解题方法
这道题的意思是:同一个字母只会出现在其中的一个片段,但是这个字符串划分为尽可能多的片段
所以,只需要把找到第一个字母’a’的最后出现的位置 x, 遍历从到 [0, x] 的所以字母的最后出现的位置为 end,这个片段就是 [0, end]
1、记录所有字母的最后一个位置
2、不断循环更新该片段的所有字母最后出现的位置
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> res = new ArrayList<>();
if (S == null || S.length() <= 0) return res;
int[] index = new int[128];
for (int i = 0; i < S.length(); i++) {
index[S.charAt(i)] = i;
}
int start = 0;
while (start < S.length()) {
int pre = start;
start = pH(S, index, pre) + 1;
res.add(start - pre);
}
return res;
}
public int pH(String S, int[] index, int start) {
int end = index[S.charAt(start)];
for (int i = start; i <= end; i++) {
if (index[S.charAt(i)] > end) end = index[S.charAt(i)];
}
return end;
}
}
执行耗时:2 ms,击败了100.00% 的Java用户
内存消耗:37.1 MB,击败了92.59% 的Java用户