fork download
  1. import java.util.HashMap;
  2. import java.util.Scanner;
  3.  
  4.  
  5. class FirstNonRepeated {
  6.  
  7. public static void main(String[] args)
  8. {
  9. String s= "stress";
  10. char c=firstNonRepeatedCharacter(s);
  11. System.out.println("The first non repeated character is : " + c);
  12. }
  13.  
  14. public static Character firstNonRepeatedCharacter(String str)
  15. {
  16. HashMap<Character,Integer> characterhashtable=
  17. new HashMap<Character ,Integer>();
  18. int i,length ;
  19. length= str.length(); // Scan string and build hash table
  20. for (i=0;i < length;i++)
  21. {
  22. c=str.charAt(i);
  23. if(characterhashtable.containsKey(c))
  24. {
  25. // increment count corresponding to c
  26. characterhashtable.put( c , characterhashtable.get(c) +1 );
  27. }
  28. else
  29. {
  30. characterhashtable.put( c , 1 ) ;
  31. }
  32. }
  33. // Search characterhashtable in in order of string str
  34.  
  35. for (i =0 ; i < length ; i++ )
  36. {
  37. c= str.charAt(i);
  38. if( characterhashtable.get(c) == 1 )
  39. return c;
  40. }
  41. return null ;
  42. }
  43. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
The first non repeated character is :  t