美文网首页
2018-10-19 First Unique Characte

2018-10-19 First Unique Characte

作者: WenshengL | 来源:发表于2018-10-20 18:38 被阅读0次
  1. First Unique Character in a String
    LC 387
    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'.

class Solution:
    """
    @param str: str: the given string
    @return: char: the first unique character in a given string
    """
    def firstUniqChar(self, str):
        counter = {}
        for i in range(len(str)):
            counter[str[i]] = counter.get(str[i], 0) + 1   
            
        for i in range(len(str)):
            if counter[str[i]] == 1:
                return str[i]
        
        return None
  • Time: O(n)
  • Space: O(n)

Note:

  1. I tried to write:
if str[i] not in counter:
    counter[str[i]] = 1
else:
    counter[str[i]] += 1

but it is better to utilize python3. Use counter.get(key, default)

  1. use counter to better describe the usage of dictionary.

相关文章

网友评论

      本文标题:2018-10-19 First Unique Characte

      本文链接:https://www.haomeiwen.com/subject/dqmmzftx.html