News:

Building a 3D Ray Tracer  By stevmjon

Main Menu

First Letter to Appear Twice

Started by kevin, September 30, 2024, 09:57:09 AM

Previous topic - Next topic

kevin

First Letter to Appear Twice

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

    A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
    s will contain at least one letter that appears twice.


    Solution #1

PlayBASIC Code: [Select]
    /*

2351. First Letter to Appear Twice

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
s will contain at least one letter that appears twice.

*/



print repeatedCharacter("abccbaacz")
print repeatedCharacter("abcdd")

Sync
waitkey


function repeatedCharacter(s$)

Dim ChrMap(26)
for lp =1 to len(s$)
ThisCHR=mid(s$,lp)
if ThisChr>=asc("a") and ThisChr<=asc("z")
Index =ThisChr-asc("a")
if ChrMap(Index)
exitfunction chr$(ThisCHR)
endif
ChrMap(Index)++
endif
next

EndFunction Result$








    Solution #2


PlayBASIC Code: [Select]
   /*

2351. First Letter to Appear Twice

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
s will contain at least one letter that appears twice.

*/



print repeatedCharacter("abccbaacz")
print repeatedCharacter("abcdd")

Sync
waitkey


function repeatedCharacter(s$)

BitMap = 0
for lp =1 to len(s$)
ThisCHR=mid(s$,lp)
if ThisChr>=asc("a") and ThisChr<=asc("z")
ThisBIT =1<< (ThisChr-asc("a"))
if BitMap & ThisBIT
exitfunction chr$(ThisCHR)
endif
BitMap |= ThisBIT
endif
next

EndFunction Result$