第一个只出现一次的字符

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

思路一

要找到第一个只出现一次的字符,那么可以一次统计字符串的每个字符出现的次数,也就是依次和后面的字符进行比较,如果只出现一次那么就输出这个字符,对于一个有n个字符的字符串,那么就可能会比较n*n次,时间复杂度为o(n^2)

思路二

import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();//这里必须要使用linkedHashMap,因为存进去的字符是有顺序的
        for(int i = 0; i < str.length(); i++){
            int count = 0;
            char c = str.charAt(i);
            if(map.containsKey(c)){
                Integer value = map.get(c);
                map.put(c, ++value);
            }else {
                map.put(c, ++count);
            }
        }
        char firstChar = 0;

        for(Map.Entry<Character,Integer> entry : map.entrySet()){
            if(entry.getValue() == 1){
                firstChar = entry.getKey();
                break;//这里找到了第一个出现一次的字符后就要退出来
            }
        }
        int index = str.indexOf(firstChar);
        return index;
    }
}

时间复杂度:o(n)

原文地址:https://www.cnblogs.com/flyingcr/p/10698546.html