[String] The first character that appears only once

Title description

Find the first character that appears only once in a string (0<=string length<=10000, all composed of letters), and return its position, if not, return -1 (case sensitive). (Counting from 0)

Enter
"google" and
return value
4


Hashing

This is the first method I thought of. Using a hash table to traverse the string once, using the character as the hash key value, and the subscript of the character as the value. If the character appears repeatedly, the value becomes 10002 (maximum Value); traverse the value of value last time and return the smallest subscript. If the smallest subscript is 10002, return -1 for all repeated characters

public int FirstNotRepeatingChar(String str) {
    
    
	HashMap<String, Integer> hashMap = new HashMap<>();
	for (int i = 0; i < str.length(); i++) {
    
    
	    String s = String.valueOf(str.charAt(i));
	    if (!hashMap.containsKey(s)) hashMap.put(s, i);
	
	    else hashMap.put(s, 10002); // repeate char
	}
	int min = 10002;
	for (int v : hashMap.values())
	    if (v < min) min = v;
	return min == 10002 ? -1 : min;
}

Optimization

Because the characters are all uppercase a~zand lowercase letters and A~Z, their ASCII codes are respectively 97~122and 65~90, a total of 52 characters. To facilitate indexing, we open up a 58-space array,Because 122-65+1=58, the subscript of the array can be directly obtained by subtracting 65 from the ASCII code of the character for operation, The array is used to store the number of occurrences of each character, traverse the string once to record the number of occurrences of each character, and finally traverse the string again to see which character appears first with the number of 1. This method uses the ASCII code of the character, and uses an array of 58 spaces to record the number of occurrences of 52 characters, and uses the extra 6 spaces in exchange for time, which is very flexible and ingenious. This method is also the idea of ​​hashing, but it only needs an array to implement it, because the key value is limited, so sometimes it is not necessary to always use a hash table.

public int FirstNotRepeatingChar(String str) {
    
    
    int count[] = new int[58];
    for (int i = 0; i < str.length(); i++)
        count[(int) str.charAt(i) - 65]++;
    for (int i = 0; i < str.length(); i++)
        if (count[(int) str.charAt(i) - 65] == 1)
            return i;
    return -1;
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/113806477