LeetCode:劃分字母區間【763】
阿新 • • 發佈:2018-08-19
math start alt ade src [] 輸出 image 小寫
LeetCode:劃分字母區間【763】
題目描述
字符串 S
由小寫字母組成。我們要把這個字符串劃分為盡可能多的片段,同一個字母只會出現在其中的一個片段。返回一個表示每個字符串片段的長度的列表。
示例 1:
輸入: S = "ababcbacadefegdehijhklij" 輸出: [9,7,8] 解釋: 劃分結果為 "ababcbaca", "defegde", "hijhklij"。 每個字母最多出現在一個片段中。 像 "ababcbacadefegde", "hijhklij" 的劃分是錯誤的,因為劃分的片段數較少。
註意:
S
的長度在[1, 500]
之間。S
只包含小寫字母‘a‘
到‘z‘
題目分析
Java題解
class Solution { public List<Integer> partitionLabels(String S) { int[] lastIndex = new int[128]; for(int i=0;i<S.length();i++) lastIndex[S.charAt(i)]=i; List<Integer> ans = new ArrayList<>(); int start =0; int end =0; for(int i=0;i<S.length();i++) { end = Math.max(end,lastIndex[S.charAt(i)]); if(i==end) { ans.add(end-start+1); start =end +1; } } return ans; } }
LeetCode:劃分字母區間【763】