题目描述: 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
s = “leetcode”
返回 0
s = “loveleetcode”
返回 2
来源:leetcode官网
原题链接
方法1 暴力求解
思路: 对字符串s中的任何一个元素,计算其在s中出现的次数,返回最早只出现一次的元素索引。
代码:
class Solution {
public int firstUniqChar(String s) {
int len = s.length();
for(int i = 0; i < len; i ++){
char s_i = s.charAt(i);
int count = 0;
for(int j = 0; j < len; j ++){
if(count > 1)
break;
else if(s.charAt(j) == s_i)
count ++;
}
if(count == 1)
return i;
}
return -1;
}
}
分析:
该方法简单粗暴,思路直接,但是时间复杂度较高,为O(n2),其中n为字符串长度。
结果:
方法2 哈希表存储次数
思路: 遍历字符串,统计每个字符出现的次数,以 <字符,次数> 形式存储在Map中;再遍历字符串,在Map中查询每个字符出现的次数,返回第一个出现次数为1的字符索引。
代码:
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> count= new HashMap<>();
int len = s.length();
for(int i = 0; i < len; i ++){
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
for(int i = 0; i < len; i ++){
if(count.get(s.charAt(i)) == 1)
return i;
}
return -1;
}
}
分析:
- 时间复杂度:相较于方法1,只有一层循环,时间复杂度为 O(n)。
- 空间复杂度: O(∣Σ∣) ,其中Σ 是字符集。因为本题中 s 只包含小写字母,因此 ∣Σ∣≤26。
结果:
方法3 哈希存储位置
思路: 遍历字符串,对于只出现一次的字符,以 <字符,位置> 的形式存储在Map中,对于出现多次的字符,以 <字符,-1> 的形式存储在Map中。然后从Map中获得位置最靠前(value最小且不为-1)的值。
代码:
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> indexes = new HashMap<>();
int len = s.length();
for(int i = 0; i < len; i ++){
if(indexes.containsKey(s.charAt(i)))
indexes.put(s.charAt(i), -1);
else
indexes.put(s.charAt(i), i);
}
int first = len;
for(Map.Entry<Character, Integer> entry : indexes.entrySet()){
int position = entry.getValue();
if(position != -1 && position < first)
first = position;
}
if(first == len)
first = -1;
return first;
}
}
分析:
时间复杂度和空间复杂度同于方法2。
结果:
方法4 使用Java方法
思路: 遍历字符串,对每一个字符,使用indexOf()和lastIndexOf()获得其在s中第一次出现和最后一次出现的位置,再比较是否相等。
代码:
class Solution {
public int firstUniqChar(String s) {
for(int i = 0; i < s.length(); i ++){
if(s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
return i;
}
return -1;
}
}
分析:
这个方法有点“钻空子”的意思,代码简单,能解题的方法暂且都视为好方法。
结果:
方法5 数组计数
思路: 类似于方法2,先定义一个int类型数组,大小为26(因为共有26种字符),数组元素索引对应字符在字母中的位置。遍历字符串,每遍历到一个字符,其对应位置的数组值就加一,代表出现的次数。再遍历字符串,从数组中找出第一个出现次数为一的字符,返回索引。
代码:
class Solution {
public int firstUniqChar(String s) {
int[] sta = new int[26];
for(int i = 0; i < s.length(); i ++){
sta[s.charAt(i) - 'a'] ++;
}
for(int i = 0; i < s.length(); i ++){
if(sta[s.charAt(i) - 'a'] == 1)
return i;
}
return -1;
}
}
分析:
- 时间复杂度:同方法2。
- 空间复杂度:O(n) ,其中n =26。
结果: