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

来源:互联网 发布:淘宝代运营 诈骗 判刑 编辑:程序博客网 时间:2024/05/17 07:32

题目:在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出‘b’。
 

算法思路:字符是一个长度为8的数据类型,因此有256种可能,所以创建一个长度为256的数组,遍历字符串,将当前字符的ASCII码值作为数组的下标,值为当前字符出现的次数,然后再次遍历字符串,找出第一个以当前字符为下标的数组中值为1的字符就是要找的字符。

#include <iostream>using namespace std;char FindNotRepeatChar(char * str){if(str==NULL)return '\0';const int length=256;unsigned int hashTable[length];//创建数组//初始化数组for(int i=0;i<length;i++){hashTable[i]=0;}//遍历字符串,记录每个字符出现的次数放在以当前字符ASCII码值为下标的数组中char * key=str;while((*key)!='\0'){hashTable[(*key)]++;key++;}//再次遍历字符串key=str;while((*key)!='\0'){if(hashTable[(*key)]==1){return (*key);}key++;}return '\0';}int main(){char * str="abaccdeft";cout<<FindNotRepeatChar(str)<<endl;return 0;}

java:

public class FindNotRepeatChar {/** * @param args */public static void main(String[] args) {char c=findNotRepeat("abcba");System.out.println(c);}public static char findNotRepeat(String str){if(str==null)return ' ';int[] count=new int[256];for(int i=0;i<count.length;i++){count[i]=0;}for(int i=0;i<str.length();i++){count[str.charAt(i)]++;}for(int i=0;i<str.length();i++){if(count[str.charAt(i)]==1)return str.charAt(i);}return ' ';}}


0 0
原创粉丝点击