1. 程式人生 > >leetcode:(763) Partitions Labels(java)

leetcode:(763) Partitions Labels(java)

題目:

    

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

 

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output:
[9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

 

Note:

  1. S will have length in range [1, 500]
    .
  2. S will consist of lowercase letters ('a' to 'z') only.

 具體程式碼及解題思路如下:

package Leetcode_Github;

import java.util.ArrayList;
import java.util.List;

public class GreedyThought_PartitionLabels_763_1109 {
    public List<Integer> PartitionLabels(String S){
        //判空
        if (S == null || S.length() == 0) {
            return new ArrayList<>();
        }
        int[] nums = new int[26];

        //從頭向後遍歷陣列,記錄字元在陣列中最後一次出現的位置
        for (int i = 0; i < S.length(); i++) {
            nums[S.charAt(i) - 'a'] = i;
        }

        List<Integer> result = new ArrayList<>();
        int firstIndex = 0; //記錄字元第一次出現的位置
        while (firstIndex < S.length()) {
            int lastIndex = firstIndex; //記錄字元最後一次出現的位置
            for (int i = firstIndex; i < S.length() && i <= lastIndex; i++) {
                int currentIndex = nums[S.charAt(i) - 'a'];
                if (currentIndex > lastIndex) {
                    lastIndex = currentIndex;
                }
            }
            result.add(lastIndex - firstIndex + 1);
            firstIndex = lastIndex + 1;
        }
        return result;
    }
}