fork download
  1. import java.util.Scanner;
  2.  
  3. class Solution {
  4. public int firstUniqChar(String s) {
  5. int[] freq = new int[26];
  6.  
  7. for (char ch : s.toCharArray()) {
  8. freq[ch - 'a']++;
  9. }
  10.  
  11. for (int i = 0; i < s.length(); i++) {
  12. if (freq[s.charAt(i) - 'a'] == 1) {
  13. return i;
  14. }
  15. }
  16.  
  17. return -1;
  18. }
  19.  
  20. public static void main(String[] args) {
  21. Scanner sc = new Scanner(System.in);
  22. String s = sc.nextLine();
  23.  
  24. Solution solution = new Solution();
  25. int index = solution.firstUniqChar(s);
  26.  
  27. if (index != -1) {
  28. System.out.println("First unique character is at index: " + index);
  29. } else {
  30. System.out.println("No unique character found.");
  31. }
  32. }
  33. }
  34.  
Success #stdin #stdout 0.18s 58948KB
stdin
loveleetcode
stdout
First unique character is at index: 2