34:第一个只出现一次的字符
问题描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
题目分析
遍历字符串,将其放到map集合中,若有重复,则value+1,然后遍历该字符串,取第一个value值为1 的下标位置
代码实现
package com.xu.fingeroffer.forty;
import java.util.HashMap;
/**
* 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数
*/
public class 第一个只出现一次的字符34 {
public static void main(String[] args) {
System.out.println(FirstNotRepeatingChar("google"));
}
public static int FirstNotRepeatingChar(String str) {
if (str==null||str.length()==0){
return -1;
}
int index=-1;
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
if(map.get(str.charAt(i))==null){
map.put(str.charAt(i),1);
}else {
map.put(str.charAt(i),map.get(str.charAt(i))+1);
}
}
for (int i = 0; i < str.length(); i++) {
if (map.get(str.charAt(i))==1){
index = i;
return index;
}
}
return index;
}
}