fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. String s = "loveleetcode";
  14. System.out.println("first unique character in string at index " + firstUnqChar(s));
  15. }
  16. static int firstUnqChar(String s){
  17. HashMap<Character,Integer> map = new HashMap<>();
  18. for(char c: s.toCharArray()){
  19. map.put(c,map.getOrDefault(c,0)+1);
  20. }
  21. for(int i=0;i<s.length();i++){
  22. char c = s.charAt(i);
  23. if(map.get(c)==1){
  24. return i;
  25. }
  26. }
  27. return -1;
  28.  
  29. }
  30. }
Success #stdin #stdout 0.15s 55700KB
stdin
Standard input is empty
stdout
first unique character in string at index 2