題目
給定一個字串,找到它的第一個不重復的字符,并回傳它的索引,如果不存在,則回傳 -1,
示例:
s = "leetcode"
回傳 0
s = "loveleetcode"
回傳 2
提示:你可以假定該字串只包含小寫字母,
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/first-unique-character-in-a-string
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
題解
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}
37ms 39.2MB
直接用Map做,思路很簡單
更多題解點擊此處
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/160254.html
標籤:其他
上一篇:Java運算子詳談
