209. First Unique Character in a String
Posted phdeblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了209. First Unique Character in a String相关的知识,希望对你有一定的参考价值。
Description
Find the first unique character in a given string. You can assume that there is at least one unique character in the string.
Example
For "abaccdeff"
, return ‘b‘
.
解题:返回仅出现一次,并且排在最前面的那个元素,而不是返回第一个不同的元素,一开始理解错了。如果仅仅对于ASCII中的256个字符,可以用数组来保存每个元素出现的次数。而对于Unicode中的元素,最好用HashMap来做。代码如下:
1 public class Solution {
2 /**
3 * @param str: str: the given string
4 * @return: char: the first unique character in a given string
5 */
6 public char firstUniqChar(String str) {
7 // Write your code here
8 HashMap<Character, Integer>map = new HashMap<Character, Integer>();
9 for(int i = 0; i < str.length(); i++){
10 char temp = str.charAt(i);
11 if(map.containsKey(temp)){
12 map.put(temp, map.get(temp) + 1);
13 }else{
14 map.put(temp, 1);
15 }
16 }
17 for(int i = 0; i < str.length(); i++)
18 if(map.get(str.charAt(i)) == 1)
19 return str.charAt(i);
20
21 return str.charAt(0);
22
23 }
24 }
以上是关于209. First Unique Character in a String的主要内容,如果未能解决你的问题,请参考以下文章
PostgreSQL:first_value(unique_column)OVER()有啥问题?
387. First Unique Character in a String
LeetCode387. First Unique Character in a String
#Leetcode# 387. First Unique Character in a String