队列:空间O(1),时间O(1)
import java.util.*;
public class Solution {
//Map<Character,Integer> map = new LinkedHashMap<>();
//Insert one char from stringstream
int[] nums = new int[128];
Queue<Character> queue = new LinkedList<>();
public void Insert(char ch)
{
if(nums[ch]++ == 0){
queue.add(ch);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
while(!queue.isEmpty()){
if(nums[queue.peek()]==1)
return queue.peek();
else queue.remove();
}
return '#';
}
}LinkedHashMap:空间O(N),时间O(1)
import java.util.*;
public class Solution {
Map<Character,Integer> map = new LinkedHashMap<>();
//Insert one char from stringstream
public void Insert(char ch)
{
if(map.containsKey(ch))
map.put(ch,map.get(ch)+1);
else
map.put(ch,1);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
for(char ch:map.keySet()){
if(map.get(ch)==1)
return ch;
}
return '#';
}
}
京公网安备 11010502036488号