[Leetcode] 387. First Unique Character in a String 解题报告

来源:互联网 发布:java技术文档怎么写 编辑:程序博客网 时间:2024/06/06 15:04

题目

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"return 0.s = "loveleetcode",return 2.

Note: You may assume the string contain only lowercase letters.

思路

首先遍历一遍,记录每个小写字符出现的次数;然后再遍历一遍,如果发现某个小写字符的出现次数是1,就返回对应索引。空间复杂度O(1),时间复杂度O(n)。

代码

class Solution {public:    int firstUniqChar(string s) {        vector<int> characters(26, 0);        for(int i = 0; i < s.length(); ++i) {            int index = s[i] - 'a';            ++characters[index];        }        for(int i = 0; i < s.length(); ++i) {            int index = s[i] - 'a';            if(characters[index] == 1) {                return i;            }        }        return -1;    }};

阅读全文
0 0