Step-by-Step

[LeetCode] 389. Find the Difference 본문

언어/JAVA

[LeetCode] 389. Find the Difference

희주(KHJ) 2023. 9. 25. 17:06

https://leetcode.com/problems/find-the-difference/?envType=daily-question&envId=2023-09-25 

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

charAt으로 비교하면 시간초과난다.

 

 

[시간초과 코드]

class Solution {
    public char findTheDifference(String s, String t) {
        int N = s.length();

        if(s.substring(0, N).equals(t.substring(0,N)))
            return t.charAt(N);

        for(int i=0; i<N; i++){
            if(s.charAt(i)!=t.charAt(i))
                return t.charAt(i);
        }

        return t.charAt(N);
    }
}

 

 

 

[char 배열 사용]

class Solution {
    public char findTheDifference(String s, String t) {
        char[] sChar = s.toCharArray();
        char[] tChar = t.toCharArray();

        HashMap<Character, Integer> hm = new HashMap<>();
        for(char ch : sChar)
            hm.put(ch, hm.getOrDefault(ch, 0)+1);

        for(char ch : tChar)
            hm.put(ch, hm.getOrDefault(ch, 0)+1);

        for(char key : hm.keySet())
            if(hm.get(key)%2!=0)
                return key;

        return t.charAt(t.length()-1);
    }
}

 

 

[가장 효율적인 해결방법]

class Solution {
    public char findTheDifference(String s, String t) {
        int num = 0;
        for(int cs : s.toCharArray()) {
            num -= cs;
        }
        for(int ct : t.toCharArray()) {
            num += ct;
        }
        return (char) (num);
    }
}

 

 

아스키 이용해서 비교하자!

Comments