字符串中的第一个唯一字符

题目描述:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历字符串

首先,如果s为null或者空字符串,直接返回-1。

如果s的长度只有1,返回索引位0。

当s的长度大于1,声明一个LinkedHashMap用来记录每个字符出现的次数,然后遍历s的每一个字符,将每一个字符和相应出现的次数放入LinkedHashMap中。

然后按顺序遍历LinkedHashMap,判断是否存在value为1即只出现过一次的字符,如果存在,返回在s中的索引位。如果遍历完发现不存在,则返回-1。

  1. import java.util.LinkedHashMap;
  2. import java.util.Map;
  3. public class LeetCode_387 {
  4. public static int firstUniqChar(String s) {
  5. if (s == null || s.length() == 0) {
  6. return -1;
  7. }
  8. if (s.length() == 1) {
  9. return 0;
  10. }
  11. Map<Character, Integer> charCount = new LinkedHashMap<>();
  12. for (char c : s.toCharArray()) {
  13. if (charCount.containsKey(c)) {
  14. charCount.put(c, charCount.get(c) + 1);
  15. } else {
  16. charCount.put(c, 1);
  17. }
  18. }
  19. for (Map.Entry<Character, Integer> characterIntegerEntry : charCount.entrySet()) {
  20. if (characterIntegerEntry.getValue() == 1) {
  21. return s.indexOf(characterIntegerEntry.getKey());
  22. }
  23. }
  24. return -1;
  25. }
  26. public static void main(String[] args) {
  27. System.out.println(firstUniqChar("loveleetcode"));
  28. }
  29. }

【每日寄语】 闪光的未必都是金子,而沉默的也不一定就是石头。