欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《剑指offer》—— 50 第一个只出现一次的字符

程序员文章站 2022-07-10 13:35:16
...

题目

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

思路
  • 利用HashMap(存储时不按顺序,找第一个不重复的字符时如果要遍历hashmap可以用LinkedHashMap;或者遍历原字符串)。
代码
import java.util.*;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str.length() <= 0) return -1;
        
        char[] ch = str.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        
        int index = 0;
        for(int i = 0; i < ch.length; i++){
            if(!map.containsKey(ch[i])){
                map.put(ch[i],1);
            }
            else{
                int count = map.get(ch[i]);
                map.put(ch[i],++count);
            }
        }
        
        //按顺序遍历字符数组,返回第一个hashmap中value=1的
        for(int i = 0; i < ch.length; i++){
            if(map.get(ch[i]) == 1)
                return i;
        }
        
        return -1;
    }
}

【类似题目】
数组中只出现一次的数字
数组中出现次数超过一半的数字

相关标签: 剑指offer