letecode [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.
题目大意:
给定字符串,找到第一个不重复的字符的下标。
理 解:
遍历字符串,统计每个元素的出现次数,再次遍历字符串,找到第一个出现一次的元素。
代 码 C++:
class Solution { public: int firstUniqChar(string s) { vector<int> count(26); for(char ch:s) count[ch-'a']++; int i = 0; while(s[i]!='\0'){ if(count[s[i]-'a']==1) return i; ++i; } return -1; } };
运行结果:
执行用时 :32 ms, 在所有 C++ 提交中击败了97.78%的用户
内存消耗 :12.9 MB, 在所有 C++ 提交中击败了85.22%的用户

浙公网安备 33010602011771号