package com
.wsq
.leetcode
;
import java
.util
.ArrayList
;
import java
.util
.HashSet
;
import java
.util
.List
;
import java
.util
.Set
;
public class PartitionLabels {
public List
<Integer> partitionLabels(String S
) {
int n
= S
.length();
int startPos
= 0;
int endPos
= 0;
int i
= 0;
List
<Integer> ans
= new ArrayList();
Set
<Character> tmpSet
= new HashSet();
while(i
< n
){
char c
= S
.charAt(i
);
endPos
= S
.lastIndexOf(c
, n
-1);
if(endPos
== -1){
ans
.add(1);
i
++;
continue;
}
int j
= i
+ 1;
tmpSet
.clear();
tmpSet
.add(c
);
while(j
< endPos
){
c
= S
.charAt(j
);
if(tmpSet
.contains(c
)){
j
++;
continue;
}
int tmpEnd
= S
.lastIndexOf(c
, n
-1);
if(tmpEnd
== -1){
continue;
}
endPos
= endPos
< tmpEnd
? tmpEnd
: endPos
;
tmpSet
.add(c
);
j
++;
}
ans
.add(endPos
- startPos
+ 1);
i
= endPos
+ 1;
startPos
= i
;
}
return ans
;
}
public static void main(String
[] args
) {
String s
= "abcdefg";
PartitionLabels pl
= new PartitionLabels();
List
<Integer> ans
= pl
.partitionLabels(s
);
for(int i
: ans
) {
System
.out
.println(i
);
}
}
}
转载请注明原文地址: https://lol.8miu.com/read-36316.html