Leetcode Interview Question 50. The first character that appears only once [time complexity is O (n), space complexity is O (26)]

Problem Description

Find the first character that appears only once in the string s. If not, return a single space.

Problem solving report

See code.
time complexity THE ( n ) O (n)
space complexity THE ( 26 ) O (26)

Implementation code

class Solution {
public:
    char firstUniqChar(string s) {
        vector<int>lastV(26,-1);
        for(int i=0;i<s.size();i++){
            if(lastV[s[i]-'a']!=-1) lastV[s[i]-'a']=INT_MAX;
            else lastV[s[i]-'a']=i;
        }
        for(int i=0;i<s.size();i++){
            if(i==lastV[s[i]-'a']) return s[i];
        }
        return ' ';
    }
};

References

[1] Leetcode Interview Question 50. The first character that appears only once

MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105477138