面试题:第一个出现的字符位置

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

方法1:哈希表

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

 

posted on 2018-08-20 16:39  Aaron12  阅读(125)  评论(0编辑  收藏  举报

导航