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

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

注意事项:您可以假定该字符串只包含小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

/**
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
*/

#include <stdio.h>
#include <stdlib.h>

/**
思路一:创建长度为26的数组,将每个字符转化为下标,并使数组指定下标的数值+1 。如:b
        事后从前往后遍历数组
*/
int firstUniqChar(char * s)
{
    int i = 0;
    int arr[26] ={0};///创建数组并且初始化数值为0

    while(s[i]!= 0){
        arr[s[i] - 'a'] ++;
        i++;
    }
    i=0;
    while(s[i]!=0){
         if(arr[s[i]-'a'] ==1 )
            return i;
        i++;

    }
    return -1;

}
int main(){
char * s = "leetcode"; ///第8位自动填充为0

printf("%d",firstUniqChar(s));
return 0;
}

发布了46 篇原创文章 · 获赞 1 · 访问量 5723

猜你喜欢

转载自blog.csdn.net/Happy_Yu_Life/article/details/105324523