g0701_0800.s0763_partition_labels.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java11 Show documentation
Show all versions of leetcode-in-java11 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
The newest version!
package g0701_0800.s0763_partition_labels;
// #Medium #Top_100_Liked_Questions #String #Hash_Table #Greedy #Two_Pointers
// #Data_Structure_II_Day_7_String #2022_03_26_Time_1_ms_(100.00%)_Space_40.3_MB_(98.19%)
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List partitionLabels(String s) {
char[] letters = s.toCharArray();
List result = new ArrayList<>();
int[] position = new int[26];
for (int i = 0; i < letters.length; i++) {
position[letters[i] - 'a'] = i;
}
int i = 0;
int prev = -1;
int max = 0;
while (i < letters.length) {
if (position[letters[i] - 'a'] > max) {
max = position[letters[i] - 'a'];
}
if (i == max) {
result.add(i - prev);
prev = i;
}
i++;
}
return result;
}
}