Game Tech Blog

443. String Compression 본문

Algorithm/LeetCode

443. String Compression

jonghow 2023. 7. 18. 01:58
반응형

[문제]

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

  • If the group's length is 1, append the character to s.
  • Otherwise, append the character followed by the group's length.

The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

 

[TC]

Example 1:

Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

Example 2:

Input: chars = ["a"]
Output: Return 1, and the first character of the input array should be: ["a"]
Explanation: The only group is "a", which remains uncompressed since it's a single character.

Example 3:

Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".

Constraints:

  • 1 <= chars.length <= 2000
  • chars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.

[접근]

접근 방식은 초기는 map 을 사용해서 중복되지 않는 것들을 모아서 카운팅 하려했으나 뒤에 이어서 나오는 TC 에서 불가능한 것을 판단, 그 예는 a,a,b,b,b,a,a 같은 경우 내가 쓴 답은 a5b3 이지만 기댓값은 a3b3a2 로 축약

방식을 변경, 바로 직전 문자와 그다음 문자가 같지않을 경우 count 초기화, 같을경우 count 증가

 

[코드] C++

class Solution {

public: vector<pair<char, int>> ret;
public: std::string str;
public: vector<char> newret;

public:
	int compress(vector<char>& chars) {

		if (chars.size() == 1) return 1;
		str = "";
		int divValue = 1000; // 2000까지니까 1000으로 나눠도 충분

		char prev = '\0';
		int Index = -1;

		for (int i = 0; i < chars.size(); ++i)
		{
			if (prev == '\0')
			{
				ret.push_back(make_pair(chars[i], 1));
				++Index;
			}
			else
			{
				if (prev == chars[i])
					ret[Index].second += 1;
				else
				{
					ret.push_back(make_pair(chars[i], 1));
					++Index;
				}
			}

			prev = chars[i];
		}

		for (auto it = ret.begin(); it != ret.end(); it++)
		{
			char input = it->first;

			str += input;
			newret.push_back(input);

			if (it->second != 1)
			{
				divValue = 1000;
				int retValue = it->second;
				int retMok = 0;
				bool isOverTens = false;

				for (int j = 1; j <= 3; ++j)
				{
					retMok = it->second / divValue;
					retValue = it->second % divValue;

					if (retMok > 0)
					{
						if (retMok % 10 == 0)
							retMok = 0;

						char convert = retMok + '0';
						str += convert;
						newret.push_back(convert);
					}
					divValue *= 0.1;
				}

				if ((isdigit(newret[newret.size() - 1]) && retValue == 0) ||
					(isdigit(newret[newret.size() - 1]) && retValue == 1) ||
					retValue > 1)
				{
					char convert = retValue + '0';
					str += convert;
					newret.push_back(convert);
				}
			}
		}

		chars = newret;
		return str.size();
	}
};

[결과]

[시도]

[후기]

상당히 금방 풀 것으로 판단되는 문제였으나, C++ 이라는 제약적인 조건과 생각지도 못한 TC 때문에 오래걸렸다.

다시 풀면 금방 풀릴것 같은 유형이기도 하다.

반응형

'Algorithm > LeetCode' 카테고리의 다른 글

11. Container With Most Water  (0) 2023.07.24
392. Is Subsequence  (0) 2023.07.20
334. Increasing Triplet Subsequence  (2) 2023.07.17
238. Product of Array Except Self  (0) 2023.07.14
151. Reverse Words in a String  (0) 2023.07.11
Comments