写一个函数,返回一个字符串中只出现一次的第一个字符 只允许遍历一次字符串

写一个函数,返回一个字符串中只出现一次的第一个字符 只允许遍历一次字符串

 char str[] = "aaabdhfrycbdhz";
int n = 0;
char arr[26];
int arr1[26];
memset(arr1, 0, 26);
for (int i = 0; i < strlen(str); i++)
{
char c = str[i];
int idx = n;
for (int j = 0; j < n; j++) if (arr[j] == c) { idx = j; break; }
arr[idx] = c;
arr1[idx]++;
}
n = -1;
while (arr1[++n] != 1);
cout << arr[n];

建议用正则表达式。很强大。

@Test
    public void test() {
        String test = "abcdefabcde";
        CTest ctest = new CTest();
        for (char c : test.toCharArray()) {
            ctest.add(c);
        }
        System.out.println(ctest.get() + "");
    }

    public static class CTest {
        List<Map<Character, Integer>> chList = new ArrayList<Map<Character, Integer>>();

        public void add(char c) {
            boolean isAdd = false;
            for (Map<Character, Integer> map : chList) {
                if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                    isAdd = true;
                    break;
                } else {
                    isAdd = false;
                }
            }
            if (!isAdd) {
                Map<Character, Integer> map = new HashMap<Character, Integer>();
                map.put(c, 1);
                chList.add(map);
            }
        }

        public char get() {
            for (Map<Character, Integer> map : chList) {
                char c = map.keySet().iterator().next();
                if (map.get(c) == 1)
                    return c;
            }
            return '0';
        }
    }


#include "stdio.h"
#include "string.h"
#include "stdlib.h"

char FirstNotRepeatingChar(char* pString)
{
    //输入不合法
    if (!pString)
        return 0;

    //创建一个哈希表,并初始化
    const int tableSize = 256;
    int hashTable[tableSize];
    for (int i = 0; i < tableSize; i++)
        hashTable[i] = 0;

    //确定字符串中每个字符出现的次数
    char* pHashKey = pString;
    while (*(pHashKey) != '\0')
        hashTable[*(pHashKey++)]++;

    //找到字符串中只出现一次的那个字符
    pHashKey = pString;
    while (*pHashKey != '\0')
    {
        if (hashTable[*pHashKey] == 1)
            return*pHashKey;
        pHashKey++;
    }

    //如果这个字符串为空,或者字符串中的每个字符都至少出现两次
    return 0;
}

int main(void)
{
    char str[1000];
    printf("请输入字符串:");
    gets(str);
    if (FirstNotRepeatingChar(str) == 0)
        printf("输入字符串中没有找到第一个只出现一次的字符!\n");
    else
        printf("输入字符串中第一个只出现一次的字符为:%c\n", FirstNotRepeatingChar(str));
    system("pause");
    return 0;
}