LeetCode题目:763. 划分字母区间

题目

题目链接:https://leetcode-cn.com/problems/partition-labels/
题目解析:通过数组将每个字母最后一个索引保存起来,根据贪心的想法,将第一个字母最后索引作为标志,如果中间有字母的最后索引大于它,就替换,然后如果遍历到字母的最后索引都没有比它更大的话,这一段就算是字母段,接着继续遍历,知道字符串结束

代码

class Solution {
    public List<Integer> partitionLabels(String S) {
    	//创建集合用于存放答案
    	List<Integer> ans = new ArrayList<Integer>();
    	//创建存放字母最后索引的数据
    	int[] lastindex = new int[26];
    	//遍历整个字符串,将字母的最后索引存放到数组中
    	for(int i=0;i<S.length();i++)
    		lastindex[S.charAt(i)-'a'] = i;
    	//用于保存当前最大索引
    	int j=0;
    	//用于保存上一个字母段的索引
    	int c=0;
    	//遍历
    	for(int i=0;i<S.length();i++) {
    		//如果当前字母的最后索引大于j,则替换
    		j = Math.max(j, lastindex[S.charAt(i)-'a']);
    		//如果遍历到j的索引,则与之前的字母为一个字母段,保存到答案集合中
    		if(i==j) {
    			ans.add(i+1-c);
    			//记录下一个开始字母的索引
    			c=i+1;
    		}
    	}
		return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41816516/article/details/106675319