From ad0acd060a9b7ca42cd1dc8a2d8c8f95c2dbda93 Mon Sep 17 00:00:00 2001 From: Leonid Date: Tue, 15 Apr 2025 11:01:48 +0300 Subject: [PATCH] FirstNonRepeatingLetter solution --- .../codewars/FirstNonRepeatingLetter.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/main/java/com/algos/codewars/FirstNonRepeatingLetter.java diff --git a/src/main/java/com/algos/codewars/FirstNonRepeatingLetter.java b/src/main/java/com/algos/codewars/FirstNonRepeatingLetter.java new file mode 100644 index 0000000..e2b21b1 --- /dev/null +++ b/src/main/java/com/algos/codewars/FirstNonRepeatingLetter.java @@ -0,0 +1,57 @@ +package com.algos.codewars; + +//Write a function named first_non_repeating_letter† that takes a string input, +// and returns the first character that is not repeated anywhere in the string. +// +// For example, if given the input 'stress', the function should return 't', +// since the letter t only occurs once in the string, and occurs first in the string. +// +// As an added challenge, upper- and lowercase letters are considered the same character, +// but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'. +// +// If a string contains all repeating characters, it should return an empty string (""); +// +// † Note: the function is called firstNonRepeatingLetter for historical reasons, +// but your function should handle any Unicode character. + + +import java.util.LinkedHashMap; +import java.util.Map; + +public class FirstNonRepeatingLetter { + + public static void main(String[] args) { + System.out.println(firstNonRepeatingLetter("manOn-aMoon")); + } + + public static String firstNonRepeatingLetter(String s) { + + if (s == null || s.isEmpty()) { + return ""; + } + + Map charCount = new LinkedHashMap<>(); + for (int i = 0; i < s.length(); i++) { + char c = Character.toLowerCase(s.charAt(i)); + charCount.merge(c, 1, Integer::sum); + } + + for (int i = 0; i < s.length(); i++) { + char currentChar = s.charAt(i); + if (charCount.get(Character.toLowerCase(currentChar)) == 1) { + return String.valueOf(currentChar); + } + } + + return ""; + +// List c = s.toLowerCase().chars().mapToObj(ch -> (char) ch).map(String::valueOf).toList(); + +// for (int i = 0; i < s.length(); i++) { +// if (Collections.frequency(c, c.get(i).toLowerCase()) == 1) { +// return String.valueOf(s.charAt(i)); +// } +// } +// return ""; + } +}