There is a string, and you need to write an algorithm that checks whether there are two identical characters in the string.

var stt = 'ABC'; var i; var a; for(i = 0; i<stt.length;i++) { for(a = 1; a<stt.length; a++) { if(stt.charAt(i) == stt.charAt(a)) { console.log('true'); } } } 

But the fact is that two of the same elements are compared and in fact, it looks like this

 if(stt.charAt(1) == stt.charAt(1)) { console.log('true'); } 

    3 answers 3

     const foo = str => /(.).*\1/.test(str); // ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° ['ABC', 'AABC', 'ABbC', 'ABCAD'].forEach(s => console.log(`'${s}': ${foo(s)}`)); 

    Another simple option:

     const bar = str => str.length !== (new Set(str)).size; 

    Algorithm (not those expressions which are higher!), Naturally on JS, for short:

     function baz(str) { const len = str.length; for (let c, i = 0; i < len; i++) { c = str.charAt(i); for (let j = i + 1; j < len; j++) { if (str.charAt(j) === c) return true; } } return false; } 
    • Regular version of the option)), but I'm afraid for the algorithm does not ride)) - Stranger in the Q
    • @StrangerintheQ, yes, because they were created just for such tasks :) By the way, I wondered if the regular schedule would turn out to be faster than other approaches ... the expression is quite simple. And about the algorithm, I will add the answer) - yar85
     var stt = 'asfafgadgjkasjfkladfkgjdflkgjkldfgj'; var temp = stt; // пСрСносим Π²ΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½ΡƒΡŽ var exist = false; // выставляСм Ρ„Π»Π°Π³ ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π±ΡƒΠ΄Π΅Ρ‚ ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΡΡ‚ΡŒ Π΅ΡΡ‚ΡŒ Π»ΠΈ Π² строкС ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹Π΅ символы for(i = 0; i < temp.length; i++){ // Ρ‚ΡƒΡ‚ всС ясно Π΄ΠΎΠ»ΠΆΠ½ΠΎ Π±Ρ‹Ρ‚ΡŒ ΠΈΠ΄Π΅ΠΌ ΠΏΠΎ строкС for(j = i+1; j < temp.length; j++){ // ΠΏΡ€ΠΎΡ…ΠΎΠ΄ΠΈΠΌ всС символы ΠΎΡ‚ Ρ‚Π΅ΠΊΡƒΡ‰Π΅Π³ΠΎ Π΄ΠΎ ΠΊΠΎΠ½Ρ†Π° строки для поиска ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹Ρ… символов if(temp[i] == temp[j]){ // само сравнСниС exist = true; // Ссли символы ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹Π΅ ΠΏΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΠΌ Ρ„Π»Π°Π³ Π² true temp = temp.split(temp[i]).join(''); // удаляСм всС ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ²Ρ‹Π΅ символы ΠΈΠ· Π²Ρ€Π΅ΠΌΠ΅Π½Π½ΠΎΠΉ строки(Π½Π΅ ΠΎΠ±ΡŒΡΠ·Π°Ρ‚Π΅Π»ΡŒΠ½ΠΎ) } } } console.log(exist); 

    For optimization, you can throw a break in the second cycle)

      I would do that:

       // Ρ€Π°Π·Π±ΠΈΠ²Π°Π΅ΠΌ строку Π½Π° символы ΠΈ примСняСм свСртку let counts = 'ABBCA'.split("").reduce((a, c) => { // считаСм символы Π² аккумуляторС return (a[c] = ++a[c] || 1) && a; },{}); // ΠΈΡ‰Π΅ΠΌ Π² Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π΅ свСртки счСтчик со Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ΠΌ большС 1 let result = Object.values(counts).filter(i => i != 1).length > 0; console.log(counts) console.log(result)