public class Solution {
public int firstUniqChar(String s) {
int[] arr = new int[26];
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 'a'] += 1;
}
for (int i = 0; i < s.length(); i++) {
if (arr[s.charAt(i) - 'a'] == 1) {
return i;
}
}
return -1;
}
}
for (int i = 0; i < s.length(); i++) {
arr[s.charAt(i) - 'a'] += 1;
}
如果是任何的字符串,而不仅仅是 26 个字母呢? 我们可以用 256 的数组来完成(因为 ASCII 码是 256)
public class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) {
return -1;
}
int[] nums = new int[256];
for (char c : s.toCharArray()) {
nums[c]++;
}
for (int i = 0; i < s.length(); i++) {
if (nums[s.charAt(i)] == 1) {
return i;
}
}
return -1;
}
}