欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > LeetCode 763. 划分字母区间 java题解

LeetCode 763. 划分字母区间 java题解

2025/7/4 3:57:20 来源:https://blog.csdn.net/weixin_42970433/article/details/146059401  浏览:    关键词:LeetCode 763. 划分字母区间 java题解

https://leetcode.cn/problems/partition-labels/description/
贪心的

class Solution {public List<Integer> partitionLabels(String s) {ArrayList<Integer> res=new ArrayList<>();//返回每个区间的长度//记录每个字母最后一次出现的位置int[] nums=new int[26];char[] chars=s.toCharArray(); for(int i=0;i<chars.length;i++){nums[chars[i]-'a']=i;}int last=-1;//上一个区间的终点int index=0;//本区间的,最大结束位置(本区间所有字母的最后位置,其中最大的一个。从这以后,不会再出现本区间字母)for(int i=0;i<chars.length;i++){index=Math.max(index,nums[chars[i]-'a']);if(index==i){//当前就是本区间最大结束位置res.add(index-last);//加入结果。[last+1,index]last=index;//更新本区间终点}}return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词