题目描述:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
题解:
1.既然该字符串只包含小写字母,那么可以用一个2行26列的整型数组temp来记录字符串中各个字母出现的次数以及最后一次出现的下标,也即用temp[0][i]表示ASCII码为97+i的小写字母在字符串中出现的次数,temp[1][i]表示该字母最后一次出现的下标。最后遍历这个二维数组,找出temp[0][i]==1时的最小的temp[1][i]即可。可以看出,时间复杂度是n+26。
代码如下:
class Solution {
public int firstUniqChar(String s) {
// 分成两种情况:
// 第一种为字符串长度小于26的,遍历字符串
if (s.length() <= 26) {
int[] charNum = new int[26];//存储各字符出现次数
char[] chars = s.toCharArray();
int length = chars.length;
for (int i = 0; i < length; i++) {//第一次遍历,记录各个字符出现次数
charNum[chars[i] - ‘a‘]++;
}
for (int i = 0; i < length; i++) {//第二次遍历,按顺序,如果次数为1,返回下标
if (charNum[chars[i] - ‘a‘] == 1) {
return i;
}
}
return -1;//无解
}
// 第二种字符串长度大于26,遍历26个字母
// 反过来,只有26个字符
int index = -1;
for (char ch = ‘a‘; ch <= ‘z‘; ch++) {
int beginIndex = s.indexOf(ch);
// 从头开始的位置是否等于结束位置,相等说明只有一个,
if (beginIndex != -1 && beginIndex == s.lastIndexOf(ch)) {
//取小的,越小代表越前。
index = (index == -1 || index > beginIndex) ? beginIndex : index;
}
}
return index;
}
}
作者:Ethan-JX
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/solution/tong-guo-zi-fu-chuan-chang-du-fen-cheng-liang-chon/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文:https://www.cnblogs.com/xbc121/p/12215945.html