首页 > 其他 > 详细

387.字符串中的第一个唯一字符

时间:2020-01-19 23:51:15      阅读:98      评论:0      收藏:0      [点我收藏+]

题目描述:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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) {
        int ans=-1;/*用于记录答案*/
        int[][]temp=new int[2][26];/*第一个数记录对应字母出现的次数,第二个数则记录其下标*/
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            int t=(int)c-97;
            temp[0][t]++;
            temp[1][t]=i;
        }
        for(int i=0;i<26;i++){
            if(temp[0][i]==1){
                ans=(ans==-1||temp[1][i]<ans)?temp[1][i]:ans;
            }
        }
        return ans;
    }
}
2.分情况,分为字符串长度小于等于26的和大于26的。小于等于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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

387.字符串中的第一个唯一字符

原文:https://www.cnblogs.com/xbc121/p/12215945.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!