您的位置:首页 > 其它

微软算法100题17 字符串中找到第一个只出现一次的字符

2015-10-24 08:44 387 查看
第17 题:
题目:在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b

思路:要找出只出现一次的字符,很明显需要统计所有字符出现的次数,然后找出次数为一的那一个,统计次数最先想到的是hashTable,但此题有更好的办法,因为每个char其实对应一个唯一的ASCII值,所以可以构造一个包含所有字符ASCII值的int数组,来映射字符与出现次数的关系,同时一个char是8个字节,总共有256个可能,所以该数组的大小应为256

package com.rui.microsoft;

public class Test17_CharStatistics {

public static void main(String[] args) {
String orig = "abaccdeff";
char res = find(orig);
System.out.println(res);
}

public static char find(String s){
char res = 0;

int[] in = new int[256];

for(int i = 0; i < s.length(); i++){
char tmp = s.charAt(i);
in[tmp]++;
}
int start = 0;
for(; start<in.length; start++){
if(in[start] == 1)break;;
}
res = (char)start;
return res;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: