First Unique Character in a String
public class Solution {
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
public char firstUniqChar(String str) {
// Write your code here
HashMap<Character, Integer> map = new HashMap<>();
Queue<Character> queue = new LinkedList<>();
for (char c : str.toCharArray()) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
queue.offer(c);
}
}
while (!queue.isEmpty() && map.get(queue.peek()) != 1) {
queue.poll();
}
return queue.peek();
}
}
最后更新于
这有帮助吗?