Problem:
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Summary:
找到字符串中第一个独一无二的字符。
Analysis:
用Hash表记录字符串中字符出现的次数,后遍历字符串,找到第一个出现次数为1的字符,返回其位置。
1 class Solution {
2 public:
3 int firstUniqChar(
string s) {
4 int len = s.size(), ch[
26] = {
0};
5
6 for (
int i =
0; i < len; i++
) {
7 int tmp = s[i] -
'a';
8 ch[tmp]++
;
9 }
10
11 for (
int i =
0; i < len; i++
) {
12 int tmp = s[i] -
'a';
13 if (ch[tmp] ==
1) {
14 return i;
15 }
16 }
17
18 return -
1;
19 }
20 };
转载于:https://www.cnblogs.com/VickyWang/p/6009776.html
相关资源:JAVA上百实例源码以及开源项目