[LintCode/LeetCode] First Unique Character in a String
文章目录
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;
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论