|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * 1286. Iterator for Combination |
| 8 | + * |
| 9 | + * Design an Iterator class, which has: |
| 10 | + * A constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments. |
| 11 | + * A function next() that returns the next combination of length combinationLength in lexicographical order. |
| 12 | + * A function hasNext() that returns True if and only if there exists a next combination. |
| 13 | + * |
| 14 | + * Example: |
| 15 | + * CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator. |
| 16 | + * iterator.next(); // returns "ab" |
| 17 | + * iterator.hasNext(); // returns true |
| 18 | + * iterator.next(); // returns "ac" |
| 19 | + * iterator.hasNext(); // returns true |
| 20 | + * iterator.next(); // returns "bc" |
| 21 | + * iterator.hasNext(); // returns false |
| 22 | + * |
| 23 | + * Constraints: |
| 24 | + * 1 <= combinationLength <= characters.length <= 15 |
| 25 | + * There will be at most 10^4 function calls per test. |
| 26 | + * It's guaranteed that all calls of the function next are valid. |
| 27 | + * */ |
| 28 | +public class _1286 { |
| 29 | + public static class Solution1 { |
| 30 | + public static class CombinationIterator { |
| 31 | + |
| 32 | + List<String> list; |
| 33 | + int index; |
| 34 | + int combinationLength; |
| 35 | + boolean[] visited; |
| 36 | + |
| 37 | + public CombinationIterator(String characters, int combinationLength) { |
| 38 | + this.index = 0; |
| 39 | + this.list = new ArrayList<>(); |
| 40 | + this.combinationLength = combinationLength; |
| 41 | + this.visited = new boolean[characters.length()]; |
| 42 | + buildAllCombinations(characters, 0, new StringBuilder(), visited); |
| 43 | + } |
| 44 | + |
| 45 | + private void buildAllCombinations(String characters, int start, StringBuilder sb, boolean[] visited) { |
| 46 | + if (sb.length() == combinationLength) { |
| 47 | + list.add(sb.toString()); |
| 48 | + return; |
| 49 | + } else { |
| 50 | + for (int i = start; i < characters.length(); ) { |
| 51 | + if (!visited[i]) { |
| 52 | + sb.append(characters.charAt(i)); |
| 53 | + visited[i] = true; |
| 54 | + buildAllCombinations(characters, i++, sb, visited); |
| 55 | + visited[i - 1] = false; |
| 56 | + sb.setLength(sb.length() - 1); |
| 57 | + } else { |
| 58 | + i++; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public String next() { |
| 65 | + return list.get(index++); |
| 66 | + } |
| 67 | + |
| 68 | + public boolean hasNext() { |
| 69 | + return index < list.size(); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments