
题目
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
解题思路
使用HashMap记录字符的出现次数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
import java.util.HashMap; public class { 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){ char c = str.charAt(i); if(map.containsKey(c)){ map.put(c, 1+map.get(c)); } else{ map.put(c, 1); } } for(int i = 0; i < str.length(); ++i){ if(map.get(str.charAt(i)) == 1){ return i; } } return -1; } }
|
近期评论