1. 题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
2. 解题思路
(1)直接遍历比较即可。(注意判断条件即可)
(2)利用LinkedHashMap保存字符和出现次数。(果然大哥牛逼)
3. 代码实现
(1)
public class Solution {
public int FirstNotRepeatingChar(String str) {
int begin = 0;
char tem;
while (begin < str.length()){
tem = str.charAt(begin);
if(str.lastIndexOf(tem) == begin && str.indexOf(tem) == begin){
return begin;
}
begin++;
}
return -1;
}
}
(2)
import java.util.LinkedHashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if (str == null || str.length() == 0)
return -1;
char[] c = str.toCharArray();
LinkedHashMap<Character,Integer> hash = new LinkedHashMap<>();
for (char item : c){
if (hash.containsKey(item))
hash.put(item, hash.get(item)+1);
else
hash.put(item,1);
}
for (int i = 0; i < str.length(); i++){
if (hash.get(str.charAt(i)) == 1){
return i;
}
}
return -1;
}
}