描述:
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
思路1:用系统给的HashMap
思路:
(1) 定义一个HashMap<Character, Integer>,键为字符,值为出现次数
(2)循环遍历字符串,取出i下标的字符,判断若该键的值为空,值改为1,否则改为值+1,循环完毕后map存的就是所有字符以及出现次数
(3)再次循环遍历字符串,判断若下标为i的键值为1,改下标对应的就是第一次出现的唯一字符,返回i,若循环完毕还没有返回值代表没找到,返回-1
代码:
class Solution {
public int firstUniqChar(String s) {
HashMap<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(map.get(ch) == null){
map.put(ch, 1);
}else{
map.put(ch, map.get(ch)+1);
}
}
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(map.get(ch) == 1){
return i;
}
}
return -1;
}
}
思路2:自己定义哈希表,利用ascll码值a为97
思路:
(1) 定义一个数组保存26个小写字母,所以数组长度26
(2)循环遍历字符串,定义ch保存第i个字符,让数组的[ch-97]下标++(数组元素默认为空,第一次遇到++后就是1,否则大于1)
(3)再次循环遍历字符串,判断若数组的[ch-97]下标的值对于1,返回当前字符串第 i 个 ,若遍历完了还没返回代表没有找到,返回-1
代码:
class Solution {
public int firstUniqChar(String s) {
int[] array = new int[26];
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
array[ch - 97]++;
}
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(array[ch - 97] == 1){
return i;
}
}
return -1;
}
}