给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
思路:一拿到就容易想到的是哈希表存所有字符出现次数吧,然后从前到后遍历字符串,返回只出现一次的字符的下标,速度很慢。穷举也能实现,但是没去写,因为应该也块不到哪儿去。还有就是前几答案中的思路,因为题目限制了都是小写字母,可以遍历26个小写字母,判断每个字母在字符串中第一次出现和最后一次出现的位置,两个位置相同的即是只出现一次的字符,在所有只出现一次的字符里面下标最小的就是答案。
两种写法的代码:
/*
HashMap解法
*/
class Solution {
public static int firstUniqChar(String s) {
HashMap<Character,Integer> hm = new HashMap<Character,Integer>();
for (int i=0;i<s.length();i++)
{
if (!hm.containsKey(s.charAt(i)))
hm.put(s.charAt(i),1);
else
hm.put(s.charAt(i),hm.get(s.charAt(i))+1);
}
for (int i=0;i<s.length();i++)
if (hm.get(s.charAt(i))==1)
return i;
return -1;
}
}
/*
判断字母位置的解法
*/
class Solution {
public int firstUniqChar(String s) {
int res = -1;
for (char ch = 'a'; ch <= 'z'; ch++) {
int index = s.indexOf(ch);
if (index != -1 && index == s.lastIndexOf(ch)) {
res = (res == -1 || res > index) ? index : res;
}
}
return res;
}
}