剑指Offer面试题50:第一个只出现一次的字符

十多分钟没看答案做完一道题,头一次。

我的思路,创建一个长度为26的int数组,存储字符出现次数。

先遍历一次字符串,计算出现次数。

再遍历一次字符串,找到第一个值为一的次数对应的字符。

答案用的hashmap,差不多,不写了

    public char firstUniqChar(String s) {
        if(s.equals("")){
            return ' ';
        }
        char[] s_c = s.toCharArray();
        int[] s_c_count = new int[26];
        for(int count = 0; count<26;count++){
            s_c_count[count] = 0;
        }
        for(int count = 0;count<s_c.length;count++){
            s_c_count[s_c[count] - 'a']++;
        }
        for(int count = 0;count<s_c.length;count++){
            if(s_c_count[s_c[count] - 'a'] == 1){
                return s_c[count];
            }
        }
        return ' ';
    }

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114635692