面试题:第一个值出现一次的字符
题目一:
在字符串中找出第一个只出现一次的字符。
如输入“abaccdeff”,则输出b
方法:
对字符串进行两次遍历,第一次:用一个字典来保存字符出现的次数;第二次:查找只出现过一次的第一次出现的字符
(书上直接用了一个256的数组来实现,因为字符是char为8bit类型)
题目二:
字符流中第一个只出现一次的字符
实现一个函数,用来找出字符流中第一个只出现一次的字符
例:
当从字符流中只读出前两个字符go时,第一个只出现一次的字符是g;
当从该字符流中读出前6个字符google时,第一个只出现一次的字符是l
方法:
依旧使用字典来保存字符出现的情况
键-字符 键值-字符出现的位置
如果字符不是第一次出现,则将位置设置为一个特殊的数,如负数
在每次需要输出当前符合条件的字符时,找出键值中最小的数,则是该字符所处位置,直接输出该字符即可
代码:
public class Q50_1 {
public static void main(String[] args) {
String s = "abaccdeff";
System.out.println(firstOnce(s));
}
public static char firstOnce(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++) {
if(map.containsKey(s.charAt(i))) {
map.put(s.charAt(i), map.get(s.charAt(i))+1);
}else {
map.put(s.charAt(i), 1);
}
}
for(int i=0;i<s.length();i++) {
if(map.get(s.charAt(i))==1) {
return s.charAt(i);
}
}
return '_';
}
}
public class Q50_2 {
public static void main(String[] args) {
firstOnce("gogooogle");
}
public static void firstOnce(String s) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++) {
if(map.containsKey(s.charAt(i))==false) {
map.put(s.charAt(i),i);
}else {
map.put(s.charAt(i),-1);
}
if(i==0) {
System.out.printf("i:%d\t%c\n",i,s.charAt(i));
}else {
int j = getFirst(map);
if(j>=0) {
System.out.printf("i:%d\t%c\n",i,s.charAt(j));
}else {
System.out.printf("i:%d\t%c\n",i,'_');
}
}
}
}
public static int getFirst(HashMap<Character,Integer> map) {
int i = 1;
int count = 0;
for(char key : map.keySet()) {
int x = map.get(key);
if(x>=0) {
if(count==0)
i = x;
if(x<i)
i = x;
count++;
}
}
if(count>0)
return i;
return -1;
}
}