Skip to content

Instantly share code, notes, and snippets.

@jbarciela
Last active May 15, 2020 12:42
Show Gist options
  • Select an option

  • Save jbarciela/5f5e4b03fc3cba5404879a5666237ca7 to your computer and use it in GitHub Desktop.

Select an option

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
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));
}
}
}
@jbarciela
Copy link
Copy Markdown
Author

jbarciela commented May 15, 2020

Output with:
String[] strs = { "abbcccadefg", "", "aaaaaaaaaaaa", "111111B111111", "1234" };
---
abbcccadefg
	Character "d" at position 7
string is null or empty
position not found in the string
111111B111111
	Character "B" at position 6
1234
	Character "1" at position 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment