Problem: https://leetcode.com/problems/first-unique-character-in-a-string/
Solution: 利用HashMap
class Solution {
public int firstUniqChar(String s) {
HashMap<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;
}
}
本文介绍了一种使用HashMap解决LeetCode题目“字符串中的第一个唯一字符”的方法。通过两次遍历字符串并利用HashMap来记录每个字符出现的次数,进而找出第一个只出现一次的字符及其位置。
938

被折叠的 条评论
为什么被折叠?



