找出字符串中第一个只出现一次的字符

来源:互联网 发布:单片机培训机构 编辑:程序博客网 时间:2024/04/27 22:31

找出字符串中第一个只出现一次的字符

解:

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

0 0