Step-by-Step
[LeetCode] 389. Find the Difference 본문
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);
}
}
아스키 이용해서 비교하자!
'언어 > JAVA' 카테고리의 다른 글
[Java] Daily LeetCode Challenge 347. Top K Frequent Elements (0) | 2023.05.23 |
---|---|
[Java] Daily LeetCode Challenge 703. Kth Largest Element in a Stream (0) | 2023.05.23 |
[Java] Daily LeetCode Challenge 2466. Count Ways To Build Good Strings (0) | 2023.05.13 |
[Java] Daily LeetCode Challenge 1035. Uncrossed Lines (0) | 2023.05.11 |
[Java] Daily LeetCode Challenge 59. Spiral Matrix II (0) | 2023.05.10 |
Comments