题目
找出第一个不重复元素的位置
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.
Note: You may assume the string contain only lowercase letters.
思路
又是重复检测类型的题目,这类题目应该都能通过线性时间复杂度的算法来解决。
通过java的集合工具类,在第一次遍历后,一定可以判断出哪些哪些元素是重复的,哪些元素是不重复的。
现在关键是如何判断这些不重复的元素中,哪一个是第一个呢?
那么就在第一次遍历的过程中把所有的不重复元素标记出来。
由此,可以选择HashMap来完成这些任务,键为字符,值为是否重复。
有了这些标记,再进行第二次遍历,返回第一个不重复元素的位置即可。
代码
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<>();
int res = -1;//默认情况:所有字符都是重复的,返回-1
for (int i = 0; i < s.length(); i++) {
if (!map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), 0);//标记置0表示还未发现重复元素
} else {//检测到重复
map.put(s.charAt(i), 1);//把标记置为1,表示这是重复元素
}
}
for (int i = 0; i < s.length(); i++) {//统计所有元素出现的次数
if (map.get(s.charAt(i)) == 0) { //只要发现不重复元素,就记录位置并退出循环
res = i;
break;
}
}
return res;
}
}
Runtime: 45 ms, faster than 41.49% of Java online submissions for First Unique Character in a String.
Memory Usage: 39.7 MB, less than 21.73% of Java online submissions for First Unique Character in a String.