package com.wsy.sword;
import java.util.LinkedHashMap;
public class FirstNotRepeatingChar
{
/*
* 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
*
* 思路:
* 直接用LinkedHashMap 存储key-value
*/
public int firstNotRepeatingChar(String str) {
if(str == null || str.length() == 0){
return -1;
}
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
int i = 0;
for (; i < str.length(); i++){
char temp = str.charAt(i);
if(map.containsKey(temp)){
int count = map.get(temp);
map.put(temp, ++count);
}else{
map.put(temp, 1);
}
}
for (i = 0; i < str.length(); i++){
if(map.get(str.charAt(i)) == 1){
return i;
}
}
return -1;
}
}
第一个只出现一次的字符
最新推荐文章于 2022-11-22 16:31:41 发布