題目:給定一個字符串,找到它的第一個不重複的字符,並返回它的索引。如果不存在,則返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.
解析:
1.定義與字符對應的數組
①定義容量爲26的數組,分別對應26個字符,a-z;
②遍歷字符串,字符出現一次,對應的數組位計數加1;
③輸出對應數組位爲1的字符下標。
public int firstUniqChar1(String s) {
//判斷輸入的合法性
if (s == null || s.length() == 0)
return -1;
//定義數組對應26個英文字母
int[] arr = new int[26];
//將字符出現的憑次放入對應的數組位
for (int i = 0; i < s.length(); i++){
arr[s.charAt(i)-'a']++;
}
for (int i = 0; i < s.length(); i++){
//如果數組位爲1,則返回回該字符的下標
if (arr[s.charAt(i)-'a'] == 1){
return i;
}
}
//否則未出現該字符
return -1;
}
2.hashmap
①建立hashmap保存字符及其對應的字符出現的頻次;
②遍歷字符串,如果hashmap中無重複字符,存儲該字符和其對應出現的頻次,如果有重複字符,將對應出現的頻次+1;
③返回hashmap中頻次爲1的字符的下標。
public int firstUniqChar2(String s){
//判斷輸入的合法性
if (s == null || s.length() == 0)
return -1;
//建立hashmap保存字符及其對應的字符出現的頻次
HashMap<Character, Integer> hashmap = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++){
//如果hashmap中沒有該字符,則加入key值=該字符,value值=1
if (!hashmap.containsKey(s.charAt(i))){
hashmap.put(s.charAt(i), 1);
}else{
//如果該字符重複出現,則將該字符的出現的頻次加1
hashmap.put(s.charAt(i), hashmap.get(s.charAt(i))+1);
}
}
//遍歷hashmap中存儲的字符,如果字符的頻次爲1,則返回該字符的下標
for (int i = 0; i < s.length(); i++){
if (hashmap.get(s.charAt(i))==1){
return i;
}
}
return -1;
}