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.
example1(sample 9 ms):
public int firstUniqChar(String s) {
int min = Integer.MAX_VALUE;
int temp = 0;
for(int i = 97; i<123; i++){
temp = s.indexOf(i);
if(temp != -1 && s.lastIndexOf(i) == temp){
min = Math.min(min, temp);
}
}
return min != Integer.MAX_VALUE ? min : -1;
}
example2(sample 10 ms):
public int firstUniqChar(String s) {
int result = Integer.MAX_VALUE;
for(int i = 97; i < 123; i++){
int idx = s.indexOf(i);
if(idx != -1 && idx == s.lastIndexOf(i)){
result = Math.min(result, idx);
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
example3(14ms):
public int firstUniqChar(String s) {
char[] b = s.toCharArray();
int[] a = new int[26];
for(int i=0;i<b.length;i++)
{
a[b[i]-'a']++;
}
for(int j=0;j<b.length;j++)
{
if(a[b[j]-'a']==1)
return j;
}
return -1;
}