[Leetcode] 2351. First Letter to Appear Twice

HyeLin·2022년 12월 11일
0
post-thumbnail

알고리즘 잊고 산지..5개월째.. 초초초 easy로 다시 돌아가서 하루에 하나씩 풀 것!!

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.

ex)
Input: s = "abccbaacz"
Output: "c"
Explanation:
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.

✔️ 연속으로 나오는 글자의 가장 첫번째 글자를 찾아 반환!

var repeatedCharacter = function(s) {
    const arr=[]
    
    for(let i of s){
     if(!arr.includes(i)){
       arr.push(i)
     }else{
       return i
     }
      }

};

✨ 빈배열에 한글자씩 체크해서, 같은 글자가 없으면 push!
✨ 그 배열에 같은 글자가 있다? 그럼 그 글자를 return!

profile
후롱트엥드 개발자

0개의 댓글