백준 5397번 std::list

김동현·2022년 6월 21일
0
#include <list> // std::list를 쓰기 위한 헤더
#include <iostream>
#include <string>

using namespace std;

int main()
{
	// 입출력 속도를 향상시킨다.
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	std::list<char> list;
	std::list<char>::iterator iter;

	int counts;
	cin >> counts;

	iter = list.end();

	string arr;

	for (int i = 0; i < counts; ++i)
	{
		cin >> arr;

		list.clear(); // 문자열에 한번 넣었으니 다시 초기화

		for (int i = 0; i < arr.length(); ++i)
		{
			switch (arr[i])
			{
			case '<':
				if (iter != list.begin())
				{
					--iter;
				}
				break;

			case '>':
				if (iter != list.end())
				{
					++iter;
				}
				break;

			case '-':
				if (iter != list.begin())
				{
					iter = list.erase(--iter);
				}
				break;
			default: // case에 안걸릴 때
				list.insert(iter, arr[i]);
				break;
			}
		}
		for (iter = list.begin(); iter != list.end(); ++iter)
		{
			cout << *iter;
		}
		cout << endl;
	}


}

switch에서 default를 처음 써봤다.
default는 case에 안걸릴 때 쓰는거더라...

문자열에 있는걸 한번 저장하고 출력한다음에 list에 있는걸 비워줘야 다시 저장하고 출력할 때 전에 있던게 사라지더라...

#include <list> // std::list를 쓰기 위한 헤더
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
	// 입출력 속도를 향상시킨다.
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	int testCase;
	cin >> testCase;
	
	while (testCase--)
	{
		// 1. 문자열을 입력 받는다
		string input;
		cin >> input;

		// 2. 컨테이너 2개를 만든다.
		// 하나는 커서 왼편에 존재하는 문자열로 정방향으로 저장

		// 다른 하나는 커서 오른편에 존재하는 문자열로 역방향으로 저장
		vector<char> left, rightReversed;

		// 3. 각 문자에 대해서 처리한다
		for (char ch : input)
		{
			switch (ch)
			{
			case '<':
				if (false == left.empty())
				{
					rightReversed.push_back(left.back());
					left.pop_back();
				}
				break;
			case '>':
				if (false == rightReversed.empty())
				{
					left.push_back(rightReversed.back());
					rightReversed.pop_back();
				}
				break;
			case '-':
				if (false == left.empty())
				{
					left.pop_back();
				}
				break;
			default:
				left.push_back(ch);
				break;
			}
		}

		cout << string(left.begin(), left.end()) << string(rightReversed.rbegin(), rightReversed.rend()) << "\n";

	}
}

교수님의 코드 컨테이너 2개를 만들어서 출력은 한 것이다.

출력부에 rbegin(), rend() 가 있는데 이것은 거꾸로 저장된 것을 출력하기 위함이다.

profile
해보자요

0개의 댓글