剑指offer49--第一个不重复的字符

来源:互联网 发布:预谋邂逅知乎 编辑:程序博客网 时间:2024/05/18 12:43

一、题目


题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。


二、举例



  例如,当从字符流中只读出前两个字符“go”时,第一个只出现一次的字符是‘g’。当从该字符流中读出前六个字符“google”时,第一个只出现1次的字符是”l”。


三、思想


(1)第一个思路是利用HashMap的方式,以键值对的形式来进行存放,但是折腾了好久发现hashmap遍历的操作有点不太适合,

不是很好进行操作,最后还是使用了万能的数组。

(2)遍历所有元素,将元素和其个数想对应,最后找到个数为1的元素即可。


四、程序



package 剑指offer;import java.io.IOException;/*  例如,当从字符流中只读出前两个字符“go”时,第一个只出现一次的字符是‘g’。 * 当从该字符流中读出前六个字符“google”时,第一个只出现1次的字符是”l”。*/public class Test55 {public static void findFirstChar(String str) throws IOException{if(str == null || str.length() < 1){System.out.println("error");}//定义一个标志位,flag==1时,表示由重复的元素int flag = 0;//定义两个数组来存储元素和对应的数目char ch[] = new char[6];int num[] = new int[6];for(int i = 0; i < str.length(); i++){//遍历一下现有数组,看是否有重复重复的元素for(int j = 0; j < ch.length; j++){if(ch[j] == str.charAt(i)){//有重复就在对应的个数上加一num[j] = num[j] + 1;flag = 1;}}//没有重复元素时if(flag == 0){ch[i] = str.charAt(i);num[i] =num[i] + 1;}flag = 0;}for(int i = 0; i < num.length; i++){if(num[i] == 1){System.out.println(ch[i]);return;}}}public static void main(String args[]) throws IOException{findFirstChar("google");findFirstChar("zyywoz");findFirstChar("moohmeh");}}

-------------output---------------

lwe




如下是两实例,一个是操作HashMap,一个是操作字符流

package 剑指offer;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class test111 {public static void main(String args[]) throws IOException{//如下是操作HashMap的程序/*HashMap<Character, Integer> hashmap = new HashMap();hashmap.put('a', 1);hashmap.put('b', 2);hashmap.put('c', 3);hashmap.put('d', 4);hashmap.put('b', 40);Iterator<Character> iter1 = hashmap.keySet().iterator();while(iter1.hasNext()){char key = (char)iter1.next();int value = (int)hashmap.get(key);System.out.println("First char is: "+key+" the value is:"+value);}*///如下是操作字符流流的实例,以前一直用readLine(),这里使用read(buf[])        FileReader fr = null;          BufferedReader br = null;        char buf[] = new char[13];        try{               fr = new FileReader("H:\\from.txt");               br = new BufferedReader(fr);                        System.out.println(fr.toString());            System.out.println(br.toString());                        int num = br.read(buf);            for(int j = 0; j < num; j++){            System.out.print(buf[j]);            }                    }          catch(IOException e){              e.toString();          }          finally{          fr.close();        br.close();        }  }}

------------------output1----------------------

char is: a  value is:1char is: b  value is:40char is: c  value is:3char is: d  value is:4

------------------output2----------------------

java.io.FileReader@139a55java.io.BufferedReader@1db9742zhangsan lisi
其中from.txt中的内容是:zhangsan lisi



1 0