第一个自出现一次的字符串(感觉有更好的解法?
第一个只出现一次的字符
http://www.nowcoder.com/questionTerminal/1c82e8cf713b4bbeb2a5b31cf5b0417c
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
hash法,k-v存字符和出现次数,然后遍历字符串取次数,如果次数为1就返回i
import java.util.*; public class Solution { public int FirstNotRepeatingChar(String str) { Map<Character, Integer> cs = new HashMap<>(); int l = str.length(); for(int i=0;i<l;i++){ Integer num = cs.get(str.charAt(i)); if(num==null){ cs.put(str.charAt(i), 1); }else { cs.put(str.charAt(i), num+1); } } for(int i=0;i<l;i++){ Integer num = cs.get(str.charAt(i)); if(num==1){ return i; } } return -1; } }