题目描述:

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。

解题思路:

  • 这道题和34.第一个只出现一次的字符位置基本上一摸一样,我们将字符串遍历放入字典中,然后遍历字典找出value值为1的便好,值得注意的是对于字典的遍历一般采用for(let [key,value] of map)来进行

解题代码:

  1. function Init()
  2. {
  3. // write code here
  4. map = new Map(); // 注意:这里不需要声明
  5. }
  6. //Insert one char from stringstream
  7. function Insert(ch)
  8. {
  9. // write code here
  10. if(!map.has(ch)) { // 注意:这里所给的是char
  11. map.set(ch,1);
  12. }else {
  13. map.set(ch,map.get(ch) + 1);
  14. }
  15. }
  16. //return the first appearence once char in current stringstream
  17. function FirstAppearingOnce()
  18. {
  19. // write code here
  20. for(let [k,v] of map) {
  21. if(v === 1) return k;
  22. }
  23. return '#'
  24. }