题解 | 第一个只出现一次的字符

第一个只出现一次的字符

https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c

import java.util.*;


public class Solution {

    // 找到第一个只出现一次的字符,并返回它的位置
    // 重点:只出现一次,第一个,所以需要整个遍历字符串
    // 还需要有序
    public int FirstNotRepeatingChar (String str) {
        // write code here
	  	// 第一个map记录索引
        HashMap<Character,Integer> map = new HashMap<>();
	  	// 第二个map记录次数
        HashMap<Character,Integer> map_count = new HashMap<>();

        int len = str.length();
        for(int i = 0; i < len; i++){
            char c = str.charAt(i);
            if(map.containsKey(c)){
                map_count.put(c,map_count.get(c) + 1);
            }else{
                map.put(c,i);
                map_count.put(c,1);
            }
        }
        for(int i = 0;i<len;i++){
            if(map_count.get(str.charAt(i)) == 1){
                return map.get(str.charAt(i));
            }
        }

        return -1;
    }
}

全部评论

相关推荐

07-01 19:00
门头沟学院 Java
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务