Skip to content

Instantly share code, notes, and snippets.

@kylelong
Last active May 22, 2019 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelong/0c99fc8fa0d8f436e9d375febbda920a to your computer and use it in GitHub Desktop.
Save kylelong/0c99fc8fa0d8f436e9d375febbda920a to your computer and use it in GitHub Desktop.
Cassido's interview question of the week 5/19/19 - Find the last non-repeating character in a given string.
import java.util.HashMap;
/**
* Created by kylel95 on 5/21/19.
* Find the last non-repeating character in a given string.
*/
public class lastUnique {
public static void main(String [] args){
String s = "candy canes do taste yummy";
String dups = "aabbcc";
System.out.println(nonRepeat(s)); //u
System.out.println(nonRepeat(dups)); //null
}
/**
* Find the last non-repeating character in a given string.
* @param s String to check
* @return the last nonrepeating character in the string
*/
public static String nonRepeat(String s){
HashMap<Character, Integer> map = new HashMap<>();
char last = ' '; //null
for(char c: s.toCharArray()){
if(!map.containsKey(c)){
map.put(c, 1);
}
else{
map.put(c, map.get(c) +1);
}
}
for(char c: s.toCharArray()){ //get last nonrepeating character
if(map.get(c) == 1){
last = c;
}
}
if(last == ' ') return null;
return String.valueOf(last);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment