剑指Offer3:第一个只出现一次的字符
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解题思路
使用HashMap集合键值对的形式存储字符串中的字母和其在字符中出现的次数。
解答
package digui;
import java.util.HashMap;
public class Demo3_Solution {
public static void main(String[] args) {
Demo3_Solution ds = new Demo3_Solution();
String str = "abcabcdd";
int index = ds.FirstNotRepeatingChar(str);
System.out.println(index);
}
public int FirstNotRepeatingChar(String str) {
HashMap<Character,Integer> hm = new HashMap<>();
char[] c = str.toCharArray();
int index = -1;
for (int i = 0; i < c.length; i++) {
if (!hm.containsKey(c[i])) {
hm.put(c[i], 1);
} else {
hm.put(c[i], hm.get(c[i])+1);
}
}
for (int i = 0; i < c.length; i++) {
if (hm.get(c[i]) == 1) {
index = i;
break;
}
}
return index;
}
}