Leetcode 387 First Unique Character in a String
Posted 琴影
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 387 First Unique Character in a String相关的知识,希望对你有一定的参考价值。
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.(小写字母)
首先这里假设只有小写字母,自然想到开一个大小为26的数组,保存每个字母出现的次数,然后在扫描一次字符串,判断出现次数是否为1,若是则直接返回小标,扫描结束后若还没有返回,说明没有字符只出现一次,返回1.
1 int firstUniqChar(char* s) { 2 int m[26] = {0}, len = strlen(s), i; 3 for(i = 0; i < len; i++){ 4 m[s[i] - \'a\']++; 5 } 6 for(i = 0; i < len; i++){ 7 if(m[s[i] - \'a\'] == 1) 8 return i; 9 } 10 return -1; 11 }
如果没有假设只包含小写字母,则可以用map
1 class Solution { 2 public: 3 int firstUniqChar(string s) { 4 int len = s.length(), i; 5 map<char, int> map1; 6 for(i = 0; i < len; i++){ 7 map1[s[i]]++; 8 } 9 for(i = 0; i < len; i++){ 10 if(map1[s[i]] == 1) 11 return i; 12 } 13 return -1; 14 } 15 };
以上是关于Leetcode 387 First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode387. First Unique Character in a String
Leetcode-387 First Unique Character in a String
LeetCode_387. First Unique Character in a String
LeetCode - 387. First Unique Character in a String