给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
示例:
提示:你可以假定该字符串只包含小写字母。
class Solution {
public int firstUniqChar(String s) {
char[] charArray = s.toCharArray();
LinkedHashSet<Character> lhs = new LinkedHashSet<Character>();
HashSet<Character> hs = new HashSet<Character>();
for(char c : charArray){
if(!hs.contains(c) && !lhs.contains(c)) lhs.add(c);
else if(lhs.contains(c)){
lhs.remove(c);
hs.add(c);
}
}
for(char c : lhs){
return s.indexOf(c);
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
char[] charArray = s.toCharArray();
int[] count = new int[26];
for(char c : charArray){
++count[c-‘a‘];
}
for(int i=0; i<s.length(); ++i){
if(count[charArray[i]-‘a‘]==1) return i;
}
return -1;
}
}
class Solution {
public int firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++)
if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
return i;
return -1;
}
}
原文:https://www.cnblogs.com/funfe/p/14812464.html