Leetcode exercise-(question number 387)

The first unique character in the string.
Given a string, find its first unique character and return its index. If it does not exist, it returns -1.
Source: LeetCode
Link: https://leetcode-cn.com/problems/linked-list-cycle

Problem-solving idea: Set up an array a[26], because there are only 26 lowercase letters in total, each letter and The difference of the ASCII code of'a' is within 26. The array is used to store the number of occurrences of each letter; the first traversal of the stored number, the second traversal to find the first unique character.

int firstUniqChar(char * s){
    
    
    int a[27]={
    
    0};
    for(int i=0;i<strlen(s);i++){
    
    
        a[s[i]-'a']++;
    }
    for(int i=0;i<strlen(s);i++){
    
    
        if(a[s[i]-'a']==1) return i;
    }
    return -1;
}

Guess you like

Origin blog.csdn.net/lthahaha/article/details/105501320