vvkpd
BAN USERprivate static String compress(String input) throws Exception {
List<Pair> occurrence = new ArrayList<>();
Arrays.stream(input.split("")).forEach(character -> {
if (!occurrence.isEmpty() && occurrence.get(occurrence.size() - 1).equals(new Pair(character, 1))) {
occurrence.get(occurrence.size() - 1).updateOccurrence();
} else {
occurrence.add(new Pair(character, 1));
}
});
String squeezedString = occurrence.stream().map(Pair::toString).collect(Collectors.joining());
if (squeezedString.length() <= input.length())
return squeezedString;
throw new Exception("Buffer overflow");
}
private static class Pair {
private final String character;
private int occurrence;
Pair(String character, int occurrence) {
this.character = character;
this.occurrence = occurrence;
}
String getCharacter() {
return character;
}
void updateOccurrence() {
occurrence = ++occurrence;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair pair = (Pair) o;
return getCharacter().equals(pair.getCharacter());
}
@Override
public int hashCode() {
return Objects.hash(getCharacter());
}
@Override
public String toString() {
return String.format("%s%s", character, occurrence);
}
}
private static Integer getLastIndexOfLastDuplicateNumber(Integer[] arr) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(arr));
for (int index = 0; index < numbers.size(); index++) {
int lastDuplicateElementIndex = numbers.lastIndexOf(numbers.get(index));
if (lastDuplicateElementIndex > -1 && lastDuplicateElementIndex != index)
return lastDuplicateElementIndex;
}
return -1;
}
private static boolean isPeriodic(String input) {
for (int charIndex = 1; charIndex <= input.length() / 2; charIndex++) {
String contentAfterSplit = String.join("", input.split(input.substring(0, charIndex)));
if (contentAfterSplit.equals(""))
return true;
}
return false;
}
- vvkpd March 27, 2019