본문 바로가기
Computer Science/알고리즘

leetcode 389) Find the Difference

by eeeun:) 2022. 2. 7.
반응형

LV. Easy 😎

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

 

문제

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

댓글