给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
学习完hashmap,利用map,key 为字符,value记录字符个数。 记录完后,遍历拿出第一个key为 1 的 下标。
class Solution {
public static int firstUniqChar(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
char [] charStr = s.toCharArray();
char ctemp;
for(int i = 0; i < charStr.length; i++) {
ctemp = charStr[i];
if(map.containsKey(ctemp)) {
int value = map.get(ctemp); //取map中 ctemp 对应的 value
map.put(ctemp,value + 1 ); //更新 value值
}else {
map.put(ctemp, 1);
}
}
//遍历charStr字符串,找在map中value第一个值为1的字符,返回charStr下标
for(int i = 0 ; i < charStr.length; i++) {
if(map.get(charStr[i]) == 1) {
return i;
}
}
return -1;
}
}
利用一维num数组保存字符出现个个数。数组索引下标0-25。 s.charAt[i] -'a’对应0-25下标。
class Solution {
public static int firstUniqChar(String s) {
int [] num = new int [26]; // 定义大小为26,保存字符个数
char [] charStr = s.toCharArray();
for(int i = 0; i < charStr.length; i++) {
num[charStr[i] - 'a'] ++; // [字符 - 'a']为字母对应 0-25区间。 用来保存字符出现个数
}
for(int i = 0 ; i < charStr.length; i++) {
if(num[charStr[i] - 'a'] == 1) { //找到字符对应数组中的数据,若找到第一个为1的返回。
return i;
}
}
return -1;
}
}