【字符串】387. 字符串中的第一个唯一字符

题目:

解答:

方法一: 线性时间复杂度解法
这道题最优的解法就是线性复杂度了,为了保证每个元素是唯一的,至少得把每个字符都遍历一遍。

算法的思路就是遍历一遍字符串,然后把字符串中每个字符出现的次数保存在一个散列表中。这个过程的时间复杂度为 O(N)O(N),其中 NN 为字符串的长度。

接下来需要再遍历一次字符串,这一次利用散列表来检查遍历的每个字符是不是唯一的。如果当前字符唯一,直接返回当前下标就可以了。第二次遍历的时间复杂度也是 O(N)O(N)。

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) 
 4     {
 5         int length = s.size();
 6         std::map<char, int> mp;
 7         
 8         // build hash map: character and how often it appears
 9         for (int i = 0; i < length; i++)
10         {
11             char cc = s[i];
12             mp[cc]++;
13         }
14 
15         // find the index
16         for (int i = 0; i < length; i++)
17         {
18             if (mp[s[i]] == 1)
19             {
20                 return i;
21             }
22         }
23 
24         return -1;
25     }
26 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12823095.html