题解 | 字符流中第一个不重复的字符

字符流中第一个不重复的字符

https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720

class Solution {
  public:
    // 哈希表,来一个字符,检查哈希表是否存在,
    // 不存在表示第一次出现则直接放入并设置成其下标表示只出现一次,若存在则把哈希表设置成-1表示出现过了
    // 在获得第一次出现时,遍历哈希表

    unordered_map<char, int> mp;
    int i = 0; //recorder the index of current sign

    //Insert one char from stringstream
    void Insert(char ch) {
        if (mp.find(ch) != mp.end()) { //found
            mp[ch] = -1; //mark
        } else { //not found
            mp[ch] = i;
        }

        i++;
    }

    //return the first appearence once char in current stringstream
    char FirstAppearingOnce() {
        char ans = '#';   //store anwser
        int index = -1; //compare
        for(auto p:mp){
            if(p.second != -1){ //means is
                if(index == -1){    //initailize
                    ans = p.first;
                    index = p.second;
                }else{
                    if(p.second < index){   //come first
                        ans = p.first;
                        index = p.second;
                    }
                }
            }
        }

        return ans;
    }

};

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务