借用计数排序的思想,构建计数数组,并将字符-'a’作为索引,最终重新遍历字符串看是不是1返回即可 public int firstUniqChar(String s) { int[] count = new int[26]; for (int i = 0; i < s.length(); i++) { count[s.charAt(i) - 'a']++; } for (int i = 0; i < s.length(); i++) { if (count[s.charAt(i) - 'a'] == 1) { return i; } } return -1; } 官方还有几种做法,也是计数排序思想,不过构建的不是计数数组,而是计数的Map,既然是Map,那对应的value既可以存出现几次,也可以直接存索引,如果多次就直接置-1。刨除这些计数排序思想,可以直接判断第一次出现的索引是不是等于最后一次出现的索引,返回。 public int firstUniqChar(String s) { for (int i = 0; i < s.length(); i++) { if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i))) { return i; } } return -1; }