Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package amazon_challange;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6.  
  7. public class Question2 {
  8.  
  9. public Question2() {
  10. }
  11.  
  12. public void solution() {
  13.  
  14. ArrayList<Character> input = new ArrayList<>();
  15. input.add('a');
  16. input.add('b');
  17. input.add('c');
  18. input.add('d');
  19. input.add('a');
  20. input.add('e');
  21. input.add('f');
  22. input.add('g');
  23. input.add('h');
  24. input.add('i');
  25. input.add('j');
  26. input.add('e');
  27. List<Integer> integers = lengthEachScene(input);
  28. System.out.println(integers);
  29. }
  30.  
  31. class Tuple implements Comparable<Tuple> {
  32. int start;
  33. int end;
  34.  
  35. public Tuple(int start, int end) {
  36. this.start = start;
  37. this.end = end;
  38. }
  39.  
  40. public void merge(Tuple other) {
  41. start = Math.min(start, other.start);
  42. end = Math.max(end, other.end);
  43. }
  44.  
  45. @Override
  46. public int compareTo(Tuple other) {
  47. return start - other.start;
  48. }
  49.  
  50. public int size() {
  51. return end - start + 1;
  52. }
  53. }
  54.  
  55. public List<Integer> lengthEachScene(List<Character> inputList) {
  56. int n = inputList.size();
  57. HashMap<Character, Integer> starts = new HashMap<Character, Integer>();
  58. HashMap<Character, Integer> ends = new HashMap<Character, Integer>();
  59.  
  60. for (int i = 0; i < n; i++) {
  61. Character c = inputList.get(i);
  62. if (!starts.containsKey(c)) {
  63. starts.put(c, i);
  64. }
  65. ends.put(c, i);
  66. }
  67.  
  68. ArrayList<Tuple> tuples = new ArrayList<>();
  69.  
  70. for (char c : inputList) {
  71. Tuple curr = new Tuple(starts.get(c), ends.get(c));
  72. Tuple find = getTuple(tuples, curr);
  73. if (find == null) tuples.add(curr);
  74. else find.merge(curr);
  75. }
  76.  
  77. ArrayList<Integer> res = new ArrayList<>();
  78. for (Tuple t : tuples) res.add(t.size());
  79. return res;
  80. }
  81.  
  82. public Tuple getTuple(List<Tuple> list, Tuple curr) {
  83. for (Tuple t : list) {
  84. if (curr.start <= t.end) return t;
  85. }
  86.  
  87. return null;
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement