当前位置:网站首页>#yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符

#yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符

2022-06-12 21:39:00 51CTO

1.简述:

描述

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

数据范围:字符串长度满足 #yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符_字符流 ,字符串中出现的字符一定在 ASCII 码内。

进阶:空间复杂度 #yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符_字符串_02 ,时间复杂度 #yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符_字符流_03

后台会用以下方式调用 Insert 和 FirstAppearingOnce 函数

string caseout = "";1.读入测试用例字符串casein2.如果对应语言有Init()函数的话,执行Init() 函数3.循环遍历字符串里的每一个字符ch {Insert(ch);caseout += FirstAppearingOnce()}2. 输出caseout,进行比较。

返回值描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

示例1

输入:

      
      
"google"
  • 1.

复制返回值:

      
      
"ggg#ll"
  • 1.

复制

示例2

输入:

      
      
"abcdee"
  • 1.

返回值:

      
      
"aaaaaa"
  • 1.

2.代码实现:

      
      
import java.util.*;
public class Solution {
private StringBuilder s = new StringBuilder();
private HashMap<Character, Integer> mp = new HashMap<>();
//Insert one char from stringstream
public void Insert(char ch)
{
//插入字符
s.append(ch);
//哈希表记录字符出现次数
mp.put(ch, mp.getOrDefault(ch, 0) + 1);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
//遍历字符串
for(int i = 0; i < s.length(); i++)
//找到第一个出现次数为1的
if(mp.get(s.charAt(i)) == 1)
return s.charAt(i);
//没有找到
return '#';
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.


原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_15488507/5376799