给定一个字符串 s
,找到它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1
。
输入: s = "leetcode" 输出: 0
解题:
(1)暴力解法
int firstUniqChar(char * s){
int length = strlen(s);
int end;
int i = 0;
here:
for(i ;i < length;i++){
for(int j = 0;j < length; j++){
if(i != j && s[i] == s[j]){
i++;
goto here;
}
}
end = i;
return end;
}
return -1;
}
(2)哈希表
class Solution {
public int firstUniqChar(String s) {
int num = 0;
HashMap<Character,Integer> map = new HashMap<>();
for(int i = 0;i < s.length(); i++){
Character ichar = s.charAt(i);
Integer count = map.getOrDefault(ichar,0) + 1;
map.put(ichar,count);
}
for(int i = 0;i < s.length(); i++){
Character ichar = s.charAt(i);
if(map.get(ichar) == 1){
return i;
}
}
return -1;
}
}
(3)indexOf( )方法→JAVA
class Solution {
public int firstUniqChar(String s) {
for(int i = 0; i < s.length() ; i++){
char ch = s.charAt(i);
if(s.indexOf(ch) == s.lastIndexOf(ch)){
return i;
}
}
return -1;
}
}
(4)String容器--find( )和rfind( )方法→C++
class Solution {
public:
int firstUniqChar(string s) {
for(int i = 0; i < s.size() ; i++){
if(s.find(s[i]) == s.rfind(s[i])){
return i;
}
}
return -1;
}
};
(5)每一个char字符和26个字母比较,将其出现次数存入数组中。找出数组中第一个值为1的元素对应的原char数组的下标
class Solution {
public int firstUniqChar(String s) {
int[] zum = new int[26];
char[] chars = s.toCharArray();
for(char ch : chars){
zum[ch - 'a']++;
}
for(int i = 0; i < chars.length; i++){
if(zum[chars[i] - 'a'] == 1)
return i;
}
return -1;
}
}