题解 | #字符流中第一个不重复的字符#
字符流中第一个不重复的字符
http://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720
思路:
1.每次取到字符后,去更新“出现一次字符的数组”,再去里面找出第一个有效字符
2.用数组存目前第一次出现的字符,新字符来了之后,用hashmap做判断
3.hashmap记载 字符-第一次出现对应的数组下标
---2的判断:取到新字符后,如果该字符存在在hashmap中,则把对应数组位置置空字符;如果不在,即第一次出现,则把当前字符加入字符数组,并更新hashmap 以当前字符为键,对应数组索引为值
import java.util.*;
public class Solution {
//Insert one char from stringstream
static ArrayList res=new ArrayList();
static HashMap res1=new HashMap();
public void Insert(char ch)
{
if(res1.get(ch)==null){
res.add(ch);
res1.put(ch,res.size()-1);
}
else{
res.set(res1.get(ch),'0');
}
}
public char FirstAppearingOnce()
{
for (char x:res) {
if(x!='0'){
return x;
}
}
return '#';
}
}
查看13道真题和解析