在一个字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)

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

思路:创建数据结构HashMap,可以记录每个字符对应出现的次数,之后遍历字符串,将对应的值存储在HashMap中,遍历完字符串后,对应字符的出现的次数也被存储,然后再次遍历字符串,找出HashMap中对应的次数,若为1,则返回对应位置。具体代码实现如下所示:

import java.util.HashMap;

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        HashMap<Character,Integer> mp=new HashMap<>();
        if(str==null){
            return -1;
        }
        for(int i=0;i<str.length();i++){
            if(mp.containsKey(str.charAt(i))){
                int value=mp.get(str.charAt(i));
                mp.put(str.charAt(i),value+1);
            }else{
                mp.put(str.charAt(i),1);
            }
        }
        for(int j=0;j<str.length();j++){
            if(mp.get(str.charAt(j))==1){
                return j;
            }
        }
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/yangmingtia/article/details/82724896
今日推荐