您的位置:首页 > 其它

在一个字符串中找到第一个只出现一次的字符

2013-04-30 23:08 337 查看
public class Test
{
public static void main(String args[])
{
String str = "abccdab";
getFirstChar(str);
}

public static void getFirstChar(String string)
{
int[] bitMap = new int[26];
char[] ch = string.toCharArray();

for (int i = 0; i < ch.length; ++i)
{
bitMap[ch[i] - 'a']++;
}

int i = 0;
while (i++ < ch.length)
{
if (bitMap[ch[i] - 'a'] == 1)
{
System.out.println(ch[i]);
break;
}
}

if (i >= ch.length)
System.out.print("sorry, there is no need what u wanted.");
}
}


空间换时间:

 

 

 

/********************************************
* 在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b
*********************************************/
#include <stdio.h>
#include <string.h>
#define N 256
int charHash
= {0};
void initCharHash(const char *s)
{
while(*s)
{
charHash[*s]++;
s++;
}
}
char findFirstOnceChar(const char *s)
{
while(*s)
{
if(charHash[*s] == 1)
{
return *s;
}
s++;
}
return 0;
}
int main(void)
{
char *str = "abaccdeff";
initCharHash(str);
printf("%c\n",findFirstOnceChar(str));
return 0;
}
/*********
b

Process returned 0 (0x0) execution time : 1.254 s
Press any key to continue.

**********/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法
相关文章推荐