From 3bc1b0d9927ad3fce5b46934e66df29026373b4f Mon Sep 17 00:00:00 2001 From: Xevion Date: Thu, 14 Jan 2021 19:35:28 -0600 Subject: [PATCH] first-unique-character-in-a-string solution java java_hashmap --- .../Solution.java | 22 +++++++++++++++++ .../Solution_HashMap.java | 24 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 first-unique-character-in-a-string/Solution.java create mode 100644 first-unique-character-in-a-string/Solution_HashMap.java diff --git a/first-unique-character-in-a-string/Solution.java b/first-unique-character-in-a-string/Solution.java new file mode 100644 index 0000000..cef8f95 --- /dev/null +++ b/first-unique-character-in-a-string/Solution.java @@ -0,0 +1,22 @@ +// Accepted +// Runtime: 7 ms +// Memory Usage: 39.6 MB +// Submitted: January 14th, 2021 + +class Solution { + public int firstUniqChar(String s) { + int[] count = new int[26]; // + int n = s.length(); + + // Count the appearances of each character + for (int i = 0; i < n; i++) + count[s.charAt(i) - 'a']++; + + // Iterate only the array again, return the index of the character that only appeared once + for (int i = 0; i < n; i++) + if (count[s.charAt(i) - 'a'] == 1) + return i; + + return -1; + } +} \ No newline at end of file diff --git a/first-unique-character-in-a-string/Solution_HashMap.java b/first-unique-character-in-a-string/Solution_HashMap.java new file mode 100644 index 0000000..4f5b035 --- /dev/null +++ b/first-unique-character-in-a-string/Solution_HashMap.java @@ -0,0 +1,24 @@ +// Accepted +// Runtime: 23 ms +// Memory Usage: 39.5 MB +// Submitted: January 14th, 2021 + +class Solution { + public int firstUniqChar(String s) { + Map count = new HashMap(); + + // Count the number of appearances of each character + for (int i = 0; i < s.length(); i++) { + char val = s.charAt(i); + count.put(val, count.getOrDefault(val, 0) + 1); + } + + // Iterate along the array again, and find the first character that only appears once + for (int i = 0; i < s.length(); i++) { + if (count.get(s.charAt(i)) == 1) + return i; + } + + return -1; + } +} \ No newline at end of file