当前位置:网站首页>#yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符
#yyds干货盘点# 解决剑指offer:字符流中第一个不重复的字符
2022-06-12 21:39:00 【51CTO】
1.简述:
描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符 "go" 时,第一个只出现一次的字符是 "g" 。当从该字符流中读出前六个字符 “google" 时,第一个只出现一次的字符是"l"。
数据范围:字符串长度满足 ,字符串中出现的字符一定在 ASCII 码内。
进阶:空间复杂度 ,时间复杂度
后台会用以下方式调用 Insert 和 FirstAppearingOnce 函数
string caseout = "";1.读入测试用例字符串casein2.如果对应语言有Init()函数的话,执行Init() 函数3.循环遍历字符串里的每一个字符ch {Insert(ch);caseout += FirstAppearingOnce()}2. 输出caseout,进行比较。
返回值描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
示例1
输入:
复制返回值:
复制
示例2
输入:
返回值:
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.
边栏推荐
猜你喜欢
SQL调优指南笔记14:Managing Extended Statistics
Distributed cloud service developer'allegro Xile technology 'received an angel round financing of US $3million
“Oracle数据库并行执行”技术白皮书读书笔记
利用ADG Standby克隆PDB
GNS installation and configuration
C language learning notes (II)
Deep Hough voting for 3D object detection in point clouds
SQL调优指南笔记15:Controlling the Use of Optimizer Statistics
Oracle LiveLabs实验:Introduction to Oracle Spatial Studio
#141 Linked List Cycle
随机推荐
Oracle数据库中查询执行计划的权限
JVisualVM初步使用
User guide for JUC concurrency Toolkit
[target detection] |dive detector into box for object detection new training method based on fcos
[QNX hypervisor 2.2 user manual] 4.3 obtain the host component
SQL tuning guide notes 8:optimizer access paths
[leetcode] 573 complex multiplication (conversion between characters and numbers)
Solve one-dimensional array prefix sum
Kdd2022 | graphmae: self supervised mask map self encoder
C language learning notes (II)
如何自己动手写一个vscode插件,实现插件自由!
冒泡排序
Gzip compression decompression
JUC并发工具包使用指南
【QNX Hypervisor 2.2 用戶手册】4.2 支持的構建環境
How do complex systems detect anomalies? North Carolina UNCC and others' latest overview of graph based deep learning anomaly detection methods in complex distributed systems describes the latest prog
zgc 并发标识和并发转移阶段的多视图地址映射
Module 8: Design message queue MySQL table for storing message data
KDD2022 | GraphMAE:自监督掩码图自编码器
DRF receives nested data and creates objects. Solution: DRF not NULL constraint failed