import java.util.*;
public class Solution {
//用于存储不重复字符的队列,队首字符就是目前队列中第一个不重复的字符
public Queue<Character> queue = new LinkedList<>();
//用来记录每个字符出现的次数,根据ASCII表可知,一共只有127个字符,固然定义数组长度为127
public int[] strs = new int[127];
//Insert one char from stringstream
public void Insert(char ch)
{
//记录ch字符的出现次数
strs[ch]++;
//将ch插入queue中
queue.add(ch);
//判断队首字符是否重复,若重复则从queue中移除
while(!queue.isEmpty() && strs[queue.peek()] > 1){
//将队首字符删除
queue.poll();
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
//若queue不为空,则返回队首字符,即第一个不重复字符;否则返回‘#’
return queue.isEmpty() ? '#' : queue.peek();
}
}
解题思路2:
public class Solution {
//用来记录每个字符出现的次数,根据ASCII表可知,一共只有127个字符,固然定义数组长度为127
int[] strs = new int[127];
//用来判断优先级,即出现的早晚
int[] priority = new int[127];
int count = 0;
//Insert one char from stringstream
public void Insert(char ch)
{
//记录ch字符的出现次数
strs[ch]++;
//保存ch第一次出现时对应的count值,count值越小,表示出现的越早
if(priority[ch] == 0){
//保存ch第一次出现时对应的count值
priority[ch] = count;
//自增
count++;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
//第一个不重复的字符
char c = '#';
//优先级
int pri = 999;
//计算第一个不重复的字符
for(int i = 0 ; i < strs.length ; i++){
//表示i字符只出现一次
if(strs[i]==1){
if(priority[i] < pri){
//i字符对应的优先级赋值给pri
pri = priority[i];
//当前第一个不重复的字符
c = (char)i;
}
}
}
return c;
}
}
解题思路3:
import java.util.*;
public class Solution {
//Insert one char from stringstream
//256大小的数组来实现一个简易的哈希表
int[] hastable = new int[256];
StringBuffer s = new StringBuffer();
public void Insert(char ch)
{
//字符添加到s中
s.append(ch);
hastable[ch]++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char[] chars = s.toString().toCharArray();
for(char c : chars){
if(hastable[c] == 1){
return c;
}
}
return '#';
}
}
解题思路1:import java.util.*;public class Solution { //用于存储不重复字符的队列,队首字符就是目前队列中第一个不重复的字符 public Queue<Character> queue = new LinkedList<>(); //用来记录每个字符出现的次数,根据ASCII表可知,一共只有127个字符,固然定义数组长度为127 public int[] strs = new int[1..