Easy
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.
37ms:
public int firstUniqChar(String s){
if(s.equals(""))
return -1;
int[] c = new int[26];
for(int i=0;i<s.length();i++){
if(c[s.charAt(i)-'a']==0)
c[s.charAt(i)-'a']=i+1;
else if(c[s.charAt(i)-'a']>0)
c[s.charAt(i)-'a'] = -1;
}
int p = s.length();
for(int j=0;j<c.length;j++){
if(c[j]>0){
p = Math.min(p, c[j]-1);
}
}
if(p==s.length())
return -1;
else
return p;
}
16ms:
public int firstUniqChar3(String s) {
int i = 1;
char[] charArray = s.toCharArray();
int[] count = new int[26];
for(char c : charArray){
if(count[c-97] == 0){
count[c-97] = i;
}else if(count[c-97] > 0){
count[c-97]-=i;
}
i++;
}
int result = i;
for(int j = 0; j < 26; j++){
if(count[j] > 0){
result = Math.min(result, count[j]-1);
}
}
if(result == i)
return -1;
return result;
}