From 3c973a8a523a8a0ecb907e357c452cd66fb734de Mon Sep 17 00:00:00 2001 From: Elena Mokeeva Date: Tue, 19 Oct 2021 19:54:43 +0200 Subject: [PATCH] chore(Java): add first non repeating character (#596) --- algorithms/Java/README.md | 1 + .../strings/first-non-repeating-char.java | 61 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 algorithms/Java/strings/first-non-repeating-char.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 621c67ef..e19b83b4 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -72,6 +72,7 @@ - [Anagram](strings/anagram.java) - [Longest Common Substring](strings/Longest_common_substring.java) - [Boyer Moore Search](strings/Boyer_Moore.java) +- [First Non Repeating Character](strings/first-non-repeating-char.java) ## Trees - [Pre in Post Traversal](trees/pre-in-post-traversal.java) diff --git a/algorithms/Java/strings/first-non-repeating-char.java b/algorithms/Java/strings/first-non-repeating-char.java new file mode 100644 index 00000000..a2756b65 --- /dev/null +++ b/algorithms/Java/strings/first-non-repeating-char.java @@ -0,0 +1,61 @@ +/* +Output the first character which occurred once in the string. +The input string can consist of any characters, like %,? or ü. +There are no constraints. For examples, see the main function. +Time Complexity: O(n) +Explanation of the algorithm: + Iterating through the string twice: + First time, the program counts occurrences into a HashMap. + Second time, the program looks for the first character + in the string with the HashMap value of 1. */ + +import java.util.*; + +public class FirstNonRepeatingChar { + + // Contains examples of usage of the algorithm + public static void main(String[] args) { + String example1 = "abcbadabfaa334"; + System.out.println(firstNonRepeatingChar(example1)); + // Output: c + + String example2 = "aab!b?cc!dü"; + System.out.println(firstNonRepeatingChar(example2)); + // Output: ? + + String example3 = "aa!b?cc!ddb?"; + System.out.println(firstNonRepeatingChar(example3)); + // Output: null + + String example4 = "üaa55vv22??1."; + System.out.println(firstNonRepeatingChar(example4)); + // Output: ü + + } + + /* + Return the first character in string a that only occurs in string a once. + If every character in the string occurs more than once, return null. + */ + public static Character firstNonRepeatingChar(String a) { + // map characters to the number of occurrences in the string + HashMap count = new HashMap<>(); + + // To iterate through the string, turn it to an array of characters + char[] charArray = a.toCharArray(); + + // Count occurrences of each character + for (Character i : charArray) { + Integer value = count.putIfAbsent(i, 0); + if (value == null) count.put(i, 1); + else count.put(i, value + 1); + } + // Search for the first matching character + for (Character k : charArray) { + if (count.get(k) == 1) { + return k; + } + } + return null; + } +}