LeetCode-387-字符串中的第一个唯一字符

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

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

示例说明请见LeetCode官网。

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

解法一:遍历字符串

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

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

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

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

import java.util.LinkedHashMap;
import java.util.Map;

public class LeetCode_387 {
    public static int firstUniqChar(String s) {
        if (s == null || s.length() == 0) {
            return -1;
        }
        if (s.length() == 1) {
            return 0;
        }
        Map<Character, Integer> charCount = new LinkedHashMap<>();
        for (char c : s.toCharArray()) {
            if (charCount.containsKey(c)) {
                charCount.put(c, charCount.get(c) + 1);
            } else {
                charCount.put(c, 1);
            }
        }
        for (Map.Entry<Character, Integer> characterIntegerEntry : charCount.entrySet()) {
            if (characterIntegerEntry.getValue() == 1) {
                return s.indexOf(characterIntegerEntry.getKey());
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(firstUniqChar("loveleetcode"));
    }
}

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

原文地址:https://www.cnblogs.com/kaesar/p/15351028.html