763.划分字母区间
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-labels
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
package cn
.little
.kitty
.demo
;
import java
.util
.ArrayList
;
import java
.util
.List
;
public class T20201022 {
public static void main(String
[] args
) {
String S
= "ababcbacadefegdehijhklij";
System
.out
.println(new T20201022().partitionLabels(S
));;
}
public List
<Integer> partitionLabels(String S
){
char [] ch
= S
.toCharArray();
List
<Integer> list
= new ArrayList<Integer>();
int index
= 0;
char c
= ' ';
while(index
< ch
.length
) {
c
= ch
[index
];
int last_c
= index
;
for (int i
= ch
.length
-1; i
> index
; i
--) {
if(ch
[i
] == c
) {
last_c
= i
;
break;
}
}
for (int i
= index
+1; i
< last_c
; i
++) {
for (int j
= last_c
+1; j
< ch
.length
; j
++) {
if (ch
[i
] == ch
[j
]) {
last_c
= j
;
}
}
}
list
.add(last_c
+1-index
);
index
= last_c
+1;
}
return list
;
}
}