描述
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
樣例
Given s = "lintcode", return 0.
Given s = "lovelintcode", return 2
代碼實(shí)現(xiàn)
public class Solution {
/**
* @param s a string
* @return it's index
*/
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
//字符是一個(gè)長度為8的數(shù)據(jù)類型,因此總共有256種可能
//每個(gè)字母根據(jù)其ASCLL碼值作為數(shù)組的下標(biāo)創(chuàng)建一個(gè)長度為256的數(shù)組
int[] str = new int[256];
for(char c : s.toCharArray()) {
str[c]++;
}
for (int i =0; i < s.length(); i++) {
if (str[s.charAt(i)] == 1) {
return i;
}
}
return -1;
}
}