字符串中的第一个唯一字符 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode” 返回 0
s = “loveleetcode” 返回 2
提示:你可以假定该字符串只包含小写字母。
使用map集合,遍历字符串,并将字符串中的每个字符和出现的次数存到map集合里,遍历集合若得到的次数值是1,则返回该字符的下标,否则返回-1.
public int firstUniqChar(String s) {
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
int n = s.length();
// build hash map : character and how often it appears
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
// find the index
for (int i = 0; i < n; i++) {
if (count.get(s.charAt(i)) == 1)
return i;
}
return -1;
}