The second day…

The title

Find the first character in the string s that occurs only once. If not, a single space is returned. The s contains only lowercase letters.

The sample

S = “abaccdeff” return “b”

S = “return “”

Train of thought

  1. Count the number of occurrences of each character
  2. The first character of degree 1 is the result of the loop count

The code

class Solution {

    / * * *@param String $s
     * @return String
     */
    function firstUniqChar($s) {
        if ($s= =' ') { return ' '; }

        $s = str_split($s);
        $counts = array_count_values($s);
        foreach ($counts as $v= >$count) {
            if ($count= = =1) {
                return $v; }}return ' '; }}Copy the code

learning

The idea of solving the problem

  1. Iterate over the string, setting the hashMap key to false if the current string already exists
  2. Loop through the hashMap, and the first key with a value of true is the answer.

The idea is roughly the same, eliminating the logic of calculating the corresponding number of times for each key, which is faster

python

class Solution:
    def firstUniqChar(self, s: str) - >str:
        dic = {}
        for c in s:
            dic[c] = not c in dic
        for k, v in dic.items():
            if v: return k
        return ' '
Copy the code

conclusion

This question focuses on the use of hashMap. It also needs to reduce some unnecessary logical calculations to save time