[Rookie Training] Sword refers to Offer 50. The first character that appears only once

Title description:

Find the first character that appears only once in the string s. If not, return a single space. s contains only lowercase letters.

Example:
s = "abaccdeff"
returns "b"

s = ""
Return" "

Limit:
0 <= length of s <= 50000

Source: LeetCode
Link: https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas:

Hash + collection. According to the requirements of the title, we need to find the first character that only appears once , which makes us think of using hash to find the character that only appears once, and the rest only needs to solve how to locate the first one. Here I add the character with the value of 1 in the hash array to the set set, and then run the loop from the front to the back for the given string s. If it is in the set, it means that this is the first one and end the loop. Output.
Since there are only 26 English letters here, we can locate them on 0-25 through the ASCII code table, which will save time and memory.

Code:

public class jianzhi_Offer_50 {
    
    
    public char firstUniqChar(String s) {
    
    
        char ans = ' ';
        if(s == "")
            return ans;
        int[] hashnum = new int[26];
        for (int i = 0 ; i < s.length(); i++){
    
    
            hashnum[s.charAt(i) - 'a']++;
        }
        Set set = new HashSet();
        for (int i = 0; i < hashnum.length; i++){
    
    
            if (hashnum[i] == 1){
    
    
                set.add((char) (i + 'a'));
            }
        }
        for (int i = 0; i < s.length(); i++){
    
    
            if (set.contains(s.charAt(i))){
    
    
                ans = s.charAt(i);
                break;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
    
    
        jianzhi_Offer_50 obj = new jianzhi_Offer_50();
        System.out.println(obj.firstUniqChar("z"));

    }
}

Guess you like

Origin blog.csdn.net/Puppet__/article/details/115196012