Find the Difference

박정현·2022년 3월 24일
0

LeetCode

목록 보기
16/18
post-thumbnail

📚 문제

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

Example 1:

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:

Input: s = "", t = "y"
Output: "y"

Constraints:

0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.

💡 풀이

var findTheDifference = function (s, t) {
    // s와 t의 요소들을 배열로 넣고 알파벳 순으로 정렬한다
    // t 배열을 반복문을 돌리면서 s에 요소가 없을 경우 그 요소를 리턴한다

    let sSort = s.split("").sort();
    let tSort = t.split("").sort();
    for (let i = 0; i < tSort.length; i++) {
        if (tSort[i] !== sSort[i]) {
            return tSort[i];
        }
    }
};

✅ 문자열로는 알파벳 순 정렬이 안되니까 배열로 바꿔서 정렬하고 반복문으로 두개의 배열 비교하면 풀리는 문제!

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글