Sword Finger Offer Interview Question 50: The first character that appears only once

It's the first time to finish a question without looking at the answer for more than ten minutes.

My idea is to create an int array with a length of 26 to store the number of occurrences of characters.

First traverse the string once and count the number of occurrences.

Traverse the string again and find the character corresponding to the number of times the first value is one.

 

The hashmap used for the answer is almost the same, so I won’t write it anymore.

 

 

 

    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 ' ';
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/114635692