现在的位置: 首页 > 综合 > 正文

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

2014年03月11日 ⁄ 综合 ⁄ 共 931字 ⁄ 字号 评论关闭
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[N] = {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.

**********/

抱歉!评论已关闭.