반응형
LV. Easy 😎
https://leetcode.com/problems/find-the-difference/
문제
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.
문제 해결법
unsigned char 값의 범위가 0 ~ 255이니깐 vector을 만들어 인덱스를 unsigned char의 값으로 해줬다.
그래서 s의 값은 해당 인덱스를 + 1 해주고, t의 값은 해당 인덱스를 -1 해줬다.
백터를 0 ~ 255 인덱스를 돌면서 -1인 값을 찾으면 그 char 값을 리턴!
해결 코드
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> s_list(255, 0);
for (int i = 0; i < s.length(); ++i) {
s_list[(unsigned char)s[i]]++;
s_list[(unsigned char)t[i]]--;
}
s_list[(unsigned char)t[t.length() - 1]]--;
for (int i = 0; i < 255; ++i) {
if (s_list[i] < 0)
return (char)i;
}
return 0;
}
};
728x90
'Computer Science > 알고리즘' 카테고리의 다른 글
leetcode 532) K-diff Pairs in an Array (0) | 2022.02.09 |
---|---|
leetcode 258) Add Digits (0) | 2022.02.08 |
leetcode 80) Remove Duplicates from Sorted Array II (0) | 2022.02.06 |
leetcode 525) Contiguous Array (0) | 2022.02.05 |
leetcode 23) Merge k Sorted Lists (0) | 2022.02.05 |
댓글