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

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

题意:给定一个字符串,返回字符串中第一个在字符串中只出现过一次的字符的下标位置,没有找到就返回-1;

解法:我们可以利用哈希表,遍历字符串,将字符及其出现的次数作为键值对存储在表中;之后,再从首部开始遍历字符串,返回对应键的值1的那个字符的下标位置;

Java
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> table = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
table.put(s.charAt(i), table.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (table.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}