每天一到算法题-字符串
白话描述:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。提示:你可以假定该字符串只包含小写字母。来源:力扣(LeetCode)链接https://leetcode-cn.com/problems/first-unique-character-in-a-string
白话实现:用hashmap 这次不浪费了 其实定义的时候加上<Character,Integer>后面就不用强制转换 (int) 了
class Solution {
public int firstUniqChar(String s) {
Map m=new HashMap();
for(int i=0;i<s.length();i++){
if(m.get(s.charAt(i))==null){
m.put(s.charAt(i),1);
}
else{
m.put(s.charAt(i),(int)(m.get(s.charAt(i)))+1);
}
}
for(int i=0;i<s.length();i++){
if((int)(m.get(s.charAt(i)))==1){
return i;
}
}
return -1;
}
}