算法实现之第一个只出现一次的字符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/byhook/article/details/79946074

题目

在字符串中找出第一个只出现一次的字符。如输入"abaccdeff",则输出b

思路

字符总共有256 种可能。

实现

public class Solution {

    public static void main(String[] args) {
        String value = "abaccdeff";
        char result = firstNotRepeating(value.toCharArray());
        System.out.println(result);
    }

    public static char firstNotRepeating(char[] chars) {
        if (chars == null || chars.length == 0) {
            return '\0';
        }
        char hashTable[] = new char[256];
        for (int i = 0; i < chars.length; i++) {
            hashTable[chars[i]] += 1;
        }
        for (int i = 0; i < chars.length; i++) {
            if (hashTable[chars[i]] == 1) {
                return chars[i];
            }
        }
        return '\0';
    }

}

猜你喜欢

转载自blog.csdn.net/byhook/article/details/79946074