From d125a1636893d67c27cddd459739f2d092f01e37 Mon Sep 17 00:00:00 2001 From: Leonid Date: Wed, 9 Apr 2025 12:33:50 +0300 Subject: [PATCH] Duplicate encoder solution --- .../com/algos/codewars/DuplicateEncoder.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/com/algos/codewars/DuplicateEncoder.java diff --git a/src/main/java/com/algos/codewars/DuplicateEncoder.java b/src/main/java/com/algos/codewars/DuplicateEncoder.java new file mode 100644 index 0000000..f3d329e --- /dev/null +++ b/src/main/java/com/algos/codewars/DuplicateEncoder.java @@ -0,0 +1,56 @@ +package com.algos.codewars; +//The goal of this exercise is to convert a string to a new string where each character in the new +// string is "(" if that character appears only once in the original string, or ")" if that character +// appears more than once in the original string. Ignore capitalization when determining if a character +// is a duplicate. +// Examples +// +// "din" => "(((" +// "recede" => "()()()" +// "Success" => ")())())" +// "(( @" => "))((" + + +import java.util.stream.Collectors; + +public class DuplicateEncoder { + + public static void main(String[] args) { + + String text = "din"; + System.out.println(encode(text)); + + text = "recede"; + System.out.println(encode(text)); + + text = "Success"; + System.out.println(encode(text)); + + text = "(( @"; + System.out.println(encode(text)); + } + + +// static String encode(String word){ +// +// Set duplicates = word.toLowerCase().chars().mapToObj(c -> (char) c) +// .collect(Collectors.groupingBy(c -> c, Collectors.counting())) +// .entrySet() +// .stream().filter(e -> e.getValue() > 1) +// .map(Map.Entry::getKey) +// .collect(Collectors.toSet()); +// +// return word.toLowerCase().chars().mapToObj(c -> (char) c).map(c -> { +// if (duplicates.contains(c)) { +// return ")"; +// } +// return "("; +// }).collect(Collectors.joining()); +// } + + static String encode(String word) { + + return word.toLowerCase().chars().mapToObj(c -> word.indexOf(c) == word.lastIndexOf(c) ? "(" : ")") + .collect(Collectors.joining()); + } +}