5

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

 2 years ago
source link: https://segmentfault.com/a/1190000040754023
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

发布于 9 月 29 日

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

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

示例说明请见LeetCode官网。

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

解法一:遍历字符串

首先,如果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"));
    }
}

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK