給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
注意事項:您可以假定該字符串只包含小寫字母。
public class Solution {
public static void main(String[] args) {
Solution solution=new Solution();
int s=solution.firstUniqChar("hellohey");
System.out.println(s);
}
public int firstUniqChar(String s) {
// //解法1: 暴力搜索, T:O(n^2)
// for (int i=0;i<s.length();i++){
// boolean isunique=true;
// for (int j=0;j<s.length();j++){
// if (j!=i&&s.charAt(i)==s.charAt(j)){
// isunique=false;
// break;
// }
// }
// if (isunique)
// return i;
// }
// return -1;
//解法2: HashMap,第一次遍歷每一個字符,統計每種字符出現的次數。第二次遍歷,找到第一齣現的字符次數爲1的字符。
Map<Character,Integer> map=new HashMap<>(s.length());
for (int i=0;i<s.length();i++){
if (!map.containsKey(s.charAt(i))){
map.put(s.charAt(i),1);
}else {
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
}
for (int i=0;i<s.length();i++){
if (map.get(s.charAt(i))==1){
return i;
}
}
return -1;
}
}