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:
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 ;
}
};
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 ;
}
};
相关文章推荐
- LeetCode 387:First Unique Character in a String
- LeetCode - First Unique Character in a String
- Leetcode 387 First Unique Character in a String
- LeetCode First Unique Character in a String
- leetcode_387 First Unique Character in a String
- 【LeetCode-387】First Unique Character in a String(C++)
- LeetCode : First Unique Character in a String
- 387.leetcode First Unique Character in a String(easy)[统计字符串字符次数]
- [LeetCode] First Unique Character in a String(Java)
- Leetcode题解:First Unique Character in a String
- LeetCode-First Unique Character in a String
- 算法系列(16)Leetcode 387 First Unique Character in a String
- leetcode[First Unique Character in a String]//待整理多种解法
- LeetCode: First Unique Character in a String
- Java [Leetcode 387]First Unique Character in a String
- [LeetCode] First Unique Character in a String 字符串第一个不同字符
- LeetCode-First Unique Character in a String
- leetcode之First Unique Character in a String
- Leetcode学习(38)—— First Unique Character in a String
- 384.[LeetCode]First Unique Character in a String