763.Partition Labels (Medium)

我的个人网站
点击可查看所有文章

找出每个字母最后出现的地方

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
public List<Integer> partitionLabels(String s) {
    
    
        int[] map = new int[26];
        int length = s.length(), end = 0, start = 0;
        List<Integer> ans = new ArrayList<>();
        for (int i = 0; i < length; i++) {
    
    
            map[s.charAt(i) - 'a'] = i;
        }
        for (int i = 0; i < length; i++) {
    
    
            end=Math.max(map[s.charAt(i) - 'a'], end);
            if(i==end){
    
    
                ans.add(end-start+1);
                start=end+1;
            }
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/qq_39644418/article/details/121950425