力扣763题(划分字母区间)
763、划分字母区间
基本思想:
贪心
具体实现:
1.统计每一个字符最后出现的位置,记录到edge数组中
2.用i从头遍历字符,idx记录这些不同的字符更靠后的最后出现的位置
比如图中a最后出现的位置是8,b最后出现的位置是5,idx记录8
分割点就是i == idx时,i的值
代码:
class Solution { public List<Integer> partitionLabels(String s) { List<Integer> list = new LinkedList<>(); int[] edge = new int[26]; char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++){ edge[chars[i] - 'a'] = i; } int idx = 0; int last = -1; for (int i = 0; i < chars.length; i++){ idx = Math.max(idx, edge[chars[i] - 'a']); if (i == idx) { list.add(i - last); last = i; } } return list; } }