|
| 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