Last active
May 22, 2019 03:56
-
-
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.
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
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