알고리즘/LeetCode

[LeetCode/easy/String] First The Difference

녕이 2022. 9. 20. 11:56
728x90

 

https://leetcode.com/problems/find-the-difference/

 

Find the Difference - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문자열 t는 문자열 s를 랜덤으로 섞어서 만들어지고 랜덤 위치에 문자를 하나 더 추가했다.

추가된 문자를 반환해라.

char findTheDifference(string s, string t) {
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());
    char c = 'a';

    for(int i=0; i<t.size(); i++){
        if(s[i] != t[i]) return t[i];
    }
    
    return c;
}

s.length 최댓값이 1000이라서, s와 t 둘 다 정렬해주고 같은 위치 값을 바라보면서 반복문을 돌렸다.

만약 다르다면 새로 들어온 값으로 반환해줬다. 

 

 

 

 

728x90