内容简介:题目地址:题目描述:
题目地址:
https://leetcode-cn.com/probl...
题目描述:
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入: S = "ababcbacadefegdehijhklij"
输出: [9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
解答:
这是一个典型的合并区间问题,我们可以记录每个字符的最小起点和最大终点,这样每个字符就形成了一个存在区间。把交叉的区间不断扩大,然后并保存,最后输出所有合并后的区间的重点-起点+1。
java ac代码:
class Solution { int[]hashmin = new int['z'+1],hashmax = new int['z'+1]; { for(int i = 'a';i <= 'z';i++) { hashmin[i] = 9999; hashmax[i] = -1; } } public List<Integer> partitionLabels(String S) { List<Integer> ans = new ArrayList(1000); for(int i = 0;i < S.length();i++) { char c = S.charAt(i); hashmin[c] = Math.min(hashmin[c],i); hashmax[c] = Math.max(hashmax[c],i); } ArrayList<Integer> list = new ArrayList(1000); for(int i = 0;i < S.length();i++) if(list.isEmpty()||hashmin[S.charAt(i)] > list.get(list.size()-1)) { list.add(hashmin[S.charAt(i)]); list.add(hashmax[S.charAt(i)]); } else list.set(list.size()-1,Math.max(list.get(list.size()-1),hashmax[S.charAt(i)])); for(int i = 0;i < list.size(); i += 2) ans.add(list.get(i+1)-list.get(i)+1); return ans; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。