码迷,mamicode.com
首页 > 其他好文 > 详细

First Unique Character in a String

时间:2016-10-25 02:03:22      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:i++   auto   and   max   pre   push   sum   char   rac   

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 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         int table[26] = {0};
 5         for (char ch : s)
 6             table[ch - a]++;
 7         
 8         for (int i = 0; i < s.size(); i++)
 9             if (table[s[i] - a] == 1) return i;
10             
11         return -1;
12     }
13 };

 

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         unordered_map<char, bool> um;
 5         for (int i = 0; i < s.size(); i++) {
 6             if (!um[s[i]] && s.find(s[i], i + 1) == s.npos) return i;
 7             um[s[i]] = true;
 8         }
 9         return -1;
10     }
11 };

 

 1 class Solution {
 2 public:
 3     int firstUniqChar(string s) {
 4         unordered_map<char, vector<int> > um;
 5         for (int i = 0; i < s.size(); i++)
 6             um[s[i]].push_back(i);
 7         
 8         int result = INT_MAX;
 9         for (auto item : um) {
10             if (item.second.size() == 1) result = min(result, item.second[0]);
11         }
12         return result == INT_MAX ? -1 : result;
13     }
14 };

 

First Unique Character in a String

标签:i++   auto   and   max   pre   push   sum   char   rac   

原文地址:http://www.cnblogs.com/amazingzoe/p/5995087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!