牛客_第一个只出现一次的字符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangvalue/article/details/87969715

题目描述

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

分析:

这个道题只是问到出现一次的情况,在考虑到遍历数组的长度比较长的时候,可以使用hashmap因为 HashMap中是不会存放相同的键的,当你存放一个map中已存在的键时会把原来的覆盖掉。这样就会统计出各个元素出现的次数,再次遍历找出次数为1.

另一种思路就是不用再次遍历原字符串,就是直接使用嵌套hashmap

hashmap将其中的value也设置为一个hashmap,被嵌套的hashmap中存储的是出现该元素的次数,和第一次该元素的位置

Map<Character,Map<Integer,Integer>> resultMap=new HashMap<Character,Map<Integer,Integer>>();
import java.util.HashMap;
import java.util.Map;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str.length()<0){return -1;}
        HashMap<Character,Integer> map= new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++){
            if(!map.containsKey(str.charAt(i))){
                map.put(str.charAt(i),1);
            }else{
           //当存在该元素直接将value增加1
            int num  =  map.get(str.charAt(i));
                map.put(str.charAt(i),++num);
            }
        }
        for(int s=0;s<str.length();s++){
            if(map.get(str.charAt(s))==1)
            return s;
        }
        // 通过Map.entrySet遍历key和value
        /*for(Map.Entry<Character, Integer> entry : map.entrySet()){
            if(entry.getValue()==1){
                return entry.getKey();
            }
        }*/
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/zhangvalue/article/details/87969715