Created
October 8, 2017 19:32
-
-
Save unilecs/cd776747d65a46c2623ada7f72a572dc to your computer and use it in GitHub Desktop.
Первый уникальный символ в строке (1 способ)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getFirstUniqueSymbol(inputStr) { | |
if (inputStr) { | |
const length = inputStr.length; | |
// частный случай: строка из 1го символа | |
if (length === 1) { | |
return inputStr; | |
} | |
// записываем в массив кол-во каждого символа: индекс элемента = код символа в строке | |
let symbolCounter = []; | |
for (let i=0; i<length; i++) { | |
const symbolCode = inputStr.charCodeAt(i); | |
if (symbolCounter[symbolCode]) { | |
symbolCounter[symbolCode] += 1; | |
} else { | |
symbolCounter[symbolCode] = 1; | |
} | |
} | |
// выводим первый уникальный символ | |
for (let i=0; i<length; i++) { | |
const symbolCode = inputStr.charCodeAt(i); | |
if (symbolCounter[symbolCode] === 1) { | |
return inputStr[i]; | |
} | |
} | |
// если не нашли уникальный символ | |
return ""; | |
} | |
return ""; | |
} | |
let uniqueSymbol = getFirstUniqueSymbol("11_22_333_4_5_4_6_7"); | |
console.info("The first unique symbol: ", uniqueSymbol !== "" ? uniqueSymbol: "not found"); // 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const getFirstUniqueSymbol = (string) => {
};