您的位置:首页 > 产品设计 > UI/UE

LeetCode No.387 First Unique Character in a String

2016-11-09 22:04 489 查看
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.

==================================================================

题目链接:https://leetcode.com/problems/first-unique-character-in-a-string/

题目大意:找出字符串中第一个不重复的字符,返回其下标,如果找不到则返回-1。

思路:用一个长度为26的数组记录各个字符的出现次数,然后遍历字符串,返回其对应个数为1的字符下标,否则返回-1。

参考代码:

class Solution {
public:
int firstUniqChar(string s) {
vector <int> nums ( 26 , 0 ) ;
int n = s.size() ;
if ( n == 0 )
return -1 ;
for ( auto& c : s )
nums[c-'a'] ++ ;
for ( int i = 0 ; i < n ; i ++ )
if ( nums[s[i]-'a'] == 1 )
return i ;
return -1 ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: