1.题目
2.解法1:每次都遍历:
public class Solution {
// String str不赋初始值为null,str += ch, ch = 'h', 会变成nullh
private String str = "";
private int[] arr = new int[128];
//Insert one char from stringstream
public void Insert(char ch) {
str += ch;
arr[ch]++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
for (int i = 0; i < str.length(); i++) {
if (arr[str.charAt(i)] == 1) {
return str.charAt(i);
}
}
return '#';
}
}
2.解法2(减少遍历次数,队列,先入先出)
字符流是动态变化的,每次都是往后插入一个元素,需要返回第一个出现1次的元素,那么需要队列来处理
import java.util.ArrayDeque;
public class Solution {
private ArrayDeque<Character> fArr = new ArrayDeque<>();
private int[] count = new int[128];
//Insert one char from stringstream
public void Insert(char ch) {
// 如果第一次出现就添加进去
if(count[ch]++ == 0) {
fArr.offer(ch);
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
Character c;
while((c = fArr.peek()) != null) {
// 判断此字符的count是不是为1
if(count[c.charValue()] == 1) {
return c;
}
// 如果不为1,移除
fArr.poll();
}
return '#';
}
}
时间复杂度为O(n),空间复杂度为O(n)