LeetCode - the first character that occurs only once (Map)

Topic description

image.png

The main question is to find the first character that appears only once. If not, it will not return an empty string, but a single space. This place is prone to errors, and everyone must pay attention.

Problem solving ideas

The blogger originally wanted to use the set to achieve it, and remove it from the set the second time it occurs, but this method cannot deal with odd numbers such as three or five occurrences. , so later adopted the simplest method of map traversal, and then stored the number of times in the value of the map, and the key is each single character.

  1. If the passed parameter is an empty string, it will be colored back to a single space.
  2. Initialize a map, iterate over each character, and update the number of occurrences of the character.
  3. Traverse each item of the map, if item[1] is equal to 1, return item[0] directly.
  4. If the third step does not find a match, return a single space.

AC code

var firstUniqChar = function (s) {
    
    
  if (s.length === 0) return " "
  const map = new Map();

  for (let v of s) {
    
    
    if (map.has(v)) {
    
    
      map.set(v,map.get(v) + 1);
    } else {
    
    
      map.set(v,1);
    }
  }

  for (let item of map) {
    
    
    if (item[1] === 1) {
    
    
      return item[0];
    }
  }
  return " "

};

Summarize

For characters that appear only once for the first time, using map is the most direct method that can be thought of. By traversing the number of occurrences of each character, you can know the characters that appear only once for the first time. So through this topic, we can consolidate the operation of the basic API of map. Here I want to emphasize what is the difference between map and traditional object? A map is similar to an object, and it is also a combination of key-value pairs, but the range of the key of a traditional object can only be a string, while the key of a map can make various types of values, including objects, as keys, that is to say, ordinary objects. Provides the correspondence between strings and values, and the map data structure provides the correspondence between values ​​and values, which is a more complete implementation of hash structure.

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/123061225