第一次只出现一次的字符 java

版权声明:博客内容为本人自己所写,请勿转载。 https://blog.csdn.net/weixin_42805929/article/details/83542666

第一次只出现一次的字符 java

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

代码1:

import java.util.*;

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        if(str.length() == 0 || str == null){
            return -1;
        }
        char[] c = str.toCharArray();
        HashMap<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < c.length; i++){
            if(map.containsKey(c[i])){
                map.put(c[i], map.get(c[i]) + 1);
            }else{
                map.put(c[i], 1);
            }
        }
        for(int i = 0; i < c.length; i++){
            if(map.get(c[i]) == 1){
                return i;
            }
        }
        return -1;
    }
}

代码2:

猜你喜欢

转载自blog.csdn.net/weixin_42805929/article/details/83542666