Problem
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Example
Given s = "lintcode", return 0.
Given s = "lovelintcode", return 2.
Tags
Amazon
Microsoft
Bloomberg
Solution
a fast way
class Solution {
public int firstUniqChar(String s) {
int[] dict = new int[26];
for (int i = 0; i < s.length(); i++) {
dict[s.charAt(i)-'a']++;
}
for (int i = 0; i < s.length(); i++) {
if (dict[s.charAt(i)-'a'] == 1) return i;
}
return -1;
}
}
a dumb way...
public class Solution {
public int firstUniqChar(String s) {
//store string in an array
char[] str = s.toCharArray();
//use HashMap to check each character's frequency
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length; i++) {
char ch = str[i];
//reset duplicate chars to '#'
if (map.containsKey(ch)) {
str[map.get(ch)] = '#';
str[i] = '#';
} else {
map.put(ch, i);
}
}
int index = str.length;
for (int i = 0; i < str.length; i++) {
//find the first character that is not '#' and return its index
if (str[i] != '#') {
return i;
}
}
//if no unique character, return -1
return -1;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。