[Leet] - 389. Find the Difference [Hash table] - c++

ha·2022년 2월 7일
0

LeetCode

목록 보기
15/21

https://leetcode.com/problems/find-the-difference/
유사문제 : leet438

C++ 알파벳 배열로 풀이법

char findTheDifference(string s, string t) {
        if(s=="")return t[0];
        char ans;
        vector<int> res(26,0); vector<int> tar(26,0);
        for(auto c : s) res[c-'a']++;
        for(auto c : t) tar[c-'a']++;
        for(int i=0;i<26;i++){
            if(res[i]!=tar[i]) 
            {
                ans=i+'a';
            }
        }
        return ans;
    }

빠른 풀이(아스키코드의 합 비교 후 차이로 구하는 법)

har findTheDifference(string s, string t) {
     int a = 0;
     int b = 0;
     for (char c : s)
         a += c;
     for (char c : t)
         b += c;
     return b - a;
 }

0개의 댓글