题目描述:
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
思路:用hashmap,键值分别存储字符和出现的次数,存储完毕之后从前向后遍历找到存储次数为一的位置
package com.niuke;
import java.util.HashMap;
/**
* Created by admin on 2018/3/17.
*/
public class FirstNotRepeatingChar {
public int firstNotRepeatingChar(String str) {
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));
map.put(str.charAt(i),++time);
} else {//不包含直接将出现的次数设置为一
map.put(str.charAt(i),1);
}
}
for (int i=0;i<str.length();i++) {
if(map.get(str.charAt(i))==1) {//存储进map完毕从头遍历找到第一个出现次数为1
return i;
}
}
return -1;
}
}