【google 2006年笔试题】 在一个字符串中找到第一个只出现一次的字符(包括普通汉字)

来源:互联网 发布:内网连接软件 编辑:程序博客网 时间:2024/04/30 06:24

参考:http://blog.csdn.net/xiaozhuyao123/article/details/7425044

开一个char范围的大小的hashTable,注意java中char占2个字节,大小为0xffff。在hashTable中统计每个字符的次数即可。

package cn.geosis.datastructure;public class HashTableTest {/** * @param args */public static void main(String[] args) {// TODO 自动生成的方法存根String testString="ccaaddddb北京bb11大学??//";getFirstMaxOccurrenceChar(testString);}/*查找第一次出现单独字符的主函数*/private static void getFirstMaxOccurrenceChar(String temString) {char[] temp=temString.toCharArray();MyHashTable myHashTable=new MyHashTable();for (char c : temp) {MyData myData=new MyData();myData.setCharData(c);myHashTable.insert(myData);}MyData[] result=MyHashTable.getHashMap();boolean flag=false;for (int i = 0; i < result.length; i++) {MyData myData = result[i];/*只要hash表中该数据不为null且计数为1则输出并跳出循环*/if (myData!=null&&myData.getCount()==1) {System.out.println("第一次出现单字符为:"+myData.getCharData());flag=true;break;}}if (flag==false) {System.out.println("不存在单字符!");}}}/*设计hash表,包含一个长度为Oxffff的数组和insert函数*/class MyHashTable{private static MyData[] hashMap=new MyData[0xffff];/*如果第一次插入,则将计数设置为1,否则计数+1*/    public void insert(MyData myData){    if (hashMap[myData.getCharData()]==null) {    myData.setCount(1);}else {myData.setCount(hashMap[myData.getCharData()].getCount()+1);}    hashMap[myData.getCharData()]=myData;            }public static MyData[] getHashMap() {return hashMap;}    }/*设计hash表中的类型,即一个字符和它的计数*/class MyData{private char charData;private int count;public char getCharData() {return charData;}public void setCharData(char charData) {this.charData = charData;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}}



0 0
原创粉丝点击