Skip to content

Commit 6e64553

Browse files
Partition Labels: Accepted
1 parent 5ff1390 commit 6e64553

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ My accepted leetcode solutions to some of the common interview problems.
186186
- [Maximum Size Subarray Sum Equals k](problems/src/hashing/MaximumSizeSubarraySumEqualsk.java) (Medium)
187187
- [Contiguous Array](problems/src/hashing/ContiguousArray.java) (Medium)
188188
- [Brick Wall](problems/src/hashing/BrickWall.java) (Medium)
189+
- [Partition Labels](problems/src/hashing/PartitionLabels.java) (Medium)
189190

190191
#### [Heap](problems/src/heap)
191192

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package hashing;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
import java.util.List;
6+
import java.util.Map;
7+
8+
/**
9+
* Created by gouthamvidyapradhan on 10/04/2018.
10+
* A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that
11+
* each letter appears in at most one part, and return a list of integers representing the size of these parts.
12+
13+
Example 1:
14+
Input: S = "ababcbacadefegdehijhklij"
15+
Output: [9,7,8]
16+
Explanation:
17+
The partition is "ababcbaca", "defegde", "hijhklij".
18+
This is a partition so that each letter appears in at most one part.
19+
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
20+
Note:
21+
22+
S will have length in range [1, 500].
23+
S will consist of lowercase letters ('a' to 'z') only.
24+
25+
Solution O(n): Maintain a hashmap index of last occurrence of a character and do a linear check for max index, get
26+
the length and add it to the result set.
27+
*/
28+
public class PartitionLabels{
29+
30+
/**
31+
* Main method
32+
* @param args
33+
* @throws Exception
34+
*/
35+
public static void main(String[] args) throws Exception{
36+
System.out.println(new PartitionLabels().partitionLabels("abc"));
37+
}
38+
39+
public List<Integer> partitionLabels(String S) {
40+
if(S == null || S.trim().isEmpty()) return new ArrayList<>();
41+
Map<Character, Integer> map = new HashMap<>();
42+
for(int i = S.length() - 1; i >= 0; i --){
43+
char c = S.charAt(i);
44+
map.putIfAbsent(c, i);
45+
}
46+
List<Integer> result = new ArrayList<>();
47+
int start = 0;
48+
int max = map.get(S.charAt(0));
49+
for(int i = 0; i < S.length(); i ++){
50+
char c = S.charAt(i);
51+
if(map.get(c) > max){
52+
max = map.get(c);
53+
} else if(i == max){
54+
result.add(max - start + 1);
55+
if(i < S.length() - 1){
56+
start = i + 1;
57+
max = map.get(S.charAt(i + 1));
58+
}
59+
}
60+
}
61+
return result;
62+
}
63+
}

0 commit comments

Comments
 (0)