34.第一次值出现一次的字符

题目描述:

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

思路分析:

  利用HashMap保存遍历字符串过程中访问到的字符和它出现的次数,然后从头遍历串,判断字符出现次数是否为1,如果为1就返回下标,否则返回-1。

代码:

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

原文地址:https://www.cnblogs.com/yjxyy/p/10841155.html