项目作者: eMahtab

项目描述 :
Find the first unique character in a string
高级语言:
项目地址: git://github.com/eMahtab/first-unique-character-in-a-string.git


First unique character in a string

https://leetcode.com/problems/first-unique-character-in-a-string

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

  1. Examples:
  2. s = "leetcode"
  3. return 0.
  4. s = "loveleetcode",
  5. return 2.

Note: You may assume the string contain only lowercase letters.

Implementation :

  1. class Solution {
  2. public int firstUniqChar(String s) {
  3. HashMap<Character, Integer> count = new HashMap<Character, Integer>();
  4. int n = s.length();
  5. // build hash map : character and how often it appears
  6. for (int i = 0; i < n; i++) {
  7. char c = s.charAt(i);
  8. count.put(c, count.getOrDefault(c, 0) + 1);
  9. }
  10. // find the index
  11. for (int i = 0; i < n; i++) {
  12. if (count.get(s.charAt(i)) == 1)
  13. return i;
  14. }
  15. return -1;
  16. }
  17. }

References :

https://leetcode.com/articles/first-unique-character-in-a-string