文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Two loops
class Solution {
public:
int firstUniqChar(string s) {
int index[256] = {0};
for(int i = 0; i < s.size(); i++) {
index[s[i]]++;
}
for(int i = 0; i < s.size(); i++) {
if(index[s[i]] == 1) {
return i;
}
}
return -1;
}
};
- Nested loop
class Solution {
public:
int firstUniqChar(string s) {
int index[256] = {0};
for(int i = 0; i < s.size(); i++) {
index[s[i]]++;
if(index[s[i]] != 1) {
continue;
}
bool flag = false;
for(int j = i + 1; j < s.size(); j++) {
if(s[i] == s[j]) {
flag = true;
break;
}
}
if(!flag) {
return i;
}
}
return -1;
}
};