您的位置:首页 > 其它

第一个只出现一次的字符

2016-03-09 17:25 218 查看
题目:在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出'b'。

思路:使用哈希表,定义哈希表的键值(Key)是字符,而值(Value)是该字符出现的次数。同时我们还需要从头开始扫描字符串两次。第一次扫描字符串时,每扫描到一个字符就在哈希表的对应项中把次数加1。接下来第二次扫描,每扫描到一个字符就能从哈希表中得到该字符出现的次数。这样第一个只出现一次的字符就是符合要求的。

package offer;

import java.util.HashMap;

/**
* 第一个只出现一次的字符
* @author zhangqd
*
*/
public class FirstNotRepeatingChar {
public static void main(String[] args) {
System.out.println(firstNotRepeat("abaccdeff"));
System.out.println(firstNotRepeat2("abaccdeff"));
}

public static char firstNotRepeat(String str){
if(str==null || str.length()==0)return ' ';
char ch = ' ';
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
for(int i=0; i<str.length(); i++){
char tmp = str.charAt(i);
if(!map.containsKey(tmp)){
map.put(tmp, 1);
}else{
int val = map.get(tmp);
map.put(tmp,val+1);
}
}
for(int j=0; j<str.length(); j++){
char tmp = str.charAt(j);
if(map.get(tmp)==1){
ch=tmp;
break;
}
}
return ch;
}

/**
* 自己建立一个哈希表
* @param str
* @return
*/
public static char firstNotRepeat2(String str){
if(str==null || str.length()==0) return ' ';
char ch = ' ';
int tableSize=256;
int[] hashTable = new int[tableSize];
int i=0;
while(i<str.length()){
hashTable[str.charAt(i)]++;
i++;
}
int j=0;
while(j<str.length()){
if(hashTable[str.charAt(j)]==1)
return str.charAt(j);
j++;
}
return ch;
}
}


如果需要判断多个字符是不是在某个字符串里出现过或者统计多个字符在某个字符串中出现的次数,我们可以考虑基于数组创建一个简单的哈希表。这样可以用很少的空间消耗换来时间效率的提升。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: