Time limit: C/C++ 1 second, other languages 2 seconds Space limit: C/C++ 64M, other languages 128M Hot index: 486021
Knowledge points of this question: String
The title description
finds the first character that appears only once in a string (0<=string length<=10000, all composed of letters), and returns its position, if not, it returns -1 (case sensitive ). (Counting from 0)
Example 1
Input
"google" and
return value
4
Idea 1: Use map to receive each string as a key, repeat the string to get the value +1, and finally traverse the map to get the element with value === 1, and it is the first one, output
Note: forEach cannot stop the loop, but map Only this kind of loop is provided, so special treatment is needed, which means && index === -1
it is a qualified element.
function FirstNotRepeatingChar(str) {
let len = str.length
let map = new Map()
for (let i = 0; i < len; i++) {
let target = map.get(str[i])
if (target) {
map.set(str[i], ++target)
} else {
map.set(str[i], 1)
}
}
let index = -1
map.forEach((val, key) => {
if (val === 1 && index === -1) {
index = str.indexOf(key)
}
})
return index
}
Idea 2: Simply use the native subscript method of finding a string. When indexOf is a positive number, and lastIndexOf is a reverse number, if they are the same, it is a unique value.
function FirstNotRepeatingChar(str) {
for(let i = 0 ; i < str.length;i++){
if(str.indexOf(str[i]) == str.lastIndexOf(str[i])) return i
}
return -1
}