Last active
May 15, 2020 12:42
-
-
Save jbarciela/5f5e4b03fc3cba5404879a5666237ca7 to your computer and use it in GitHub Desktop.
Given a sequence of characters, find the first character that occurs exactly once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.jbarciela.frolic; | |
| import java.util.ArrayList; | |
| import java.util.HashMap; | |
| import java.util.List; | |
| /** | |
| * Given a sequence of characters, find the first character that occurs exactly once. | |
| * | |
| * @author jbarciela | |
| * | |
| */ | |
| public class FindFirstUnique { | |
| private boolean nullOrEmpty(String s) { | |
| return ((null == s) || s.isEmpty()) ? true : false; | |
| } | |
| public int findFirstUniquePosition(String str) { | |
| if (nullOrEmpty(str)) { | |
| return -1; | |
| } | |
| var counts = new HashMap<Character, List<Integer>>(); | |
| for (int pos = 0; pos < str.length(); pos++) { | |
| var currChar = str.charAt(pos); | |
| if (counts.containsKey(currChar)) { | |
| counts.get(currChar).add(pos); | |
| } else { | |
| var l = new ArrayList<Integer>(); | |
| l.add(pos); | |
| counts.put(currChar, l); | |
| } | |
| } | |
| var minPos = Integer.MAX_VALUE; | |
| var found = false; | |
| for (var positions : counts.values()) { | |
| if (positions.size() == 1) { | |
| minPos = Math.min(minPos, positions.get(0)); | |
| found = true; | |
| } | |
| } | |
| return (found) ? minPos : -1; | |
| } | |
| public void print(String str, int pos) { | |
| if (nullOrEmpty(str)) { | |
| System.out.println("string is null or empty"); | |
| } else if ((pos < 0) || (pos >= str.length())) { | |
| System.out.println("position not found in the string"); | |
| } else { | |
| System.out.println(str); | |
| System.out.println("\tCharacter \"" + str.charAt(pos) + "\" at position " + pos); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| var ffu = new FindFirstUnique(); | |
| String[] strs = { "abbcccadefg", "", "aaaaaaaaaaaa", "111111B111111", "1234" }; | |
| for (var s : strs) { | |
| ffu.print(s, ffu.findFirstUniquePosition(s)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.