剑指offer第二版——面试题50(java)

面试题:第一个值出现一次的字符

题目一:

在字符串中找出第一个只出现一次的字符。

如输入“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;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值