描述
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
代码实现
public class Solution {
/**
* @param s a string
* @return it's index
*/
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
//字符是一个长度为8的数据类型,因此总共有256种可能
//每个字母根据其ASCLL码值作为数组的下标创建一个长度为256的数组
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;
}
}