백준10988 - 팰린드롬인지 확인하기.

phoenixKim·2022년 5월 17일
0

백준 알고리즘

목록 보기
25/174

여러가지 푸는 방법이 있는데, 영 안맞다 싶으면 변경하자.

  • reverse 하는 방식으로 접근한 코드
#include <iostream>
#include <vector>
using namespace std;
#include <algorithm>
#include <queue>
#include <string>
#include <map>



//int alpha[26];


int main()
{
	string s;
	cin >> s;

	map<char, int >mm;
	for (auto iter : s)
	{
		//++alpha[iter - 'A'];
		mm[iter]++;
	}

	char midIndex = '0';
	//for (int i = 0; i < 26; ++i)
	//{
	//	if (alpha[i] % 2 != 0)
	//	{
	//		if (midIndex != -1)
	//		{
	//			cout << "I'm Sorry Hansoo";
	//			return 0;
	//		}
	//		midIndex = i;
	//	}
	//}
	string front = "";
	string post = "";

	for (auto iter : mm)
	{
		if (iter.second % 2 != 0)
		{
			if (midIndex != '0')
			{
				cout << "I'm Sorry Hansoo";
				return 0;
			}
			midIndex = iter.first;
		}

		int cnt = iter.second;
		for (int i = 0; i < cnt / 2; ++i)
		{
			front += iter.first;
			post += iter.first;
		}

	}
	reverse(post.begin(), post.end());

	if (midIndex == '0')
	{
		cout << front + post;
	}
	else
		cout << front + midIndex + post;
	

	// 앞부분 

	
	
	

}

시간 복잡도

: 시간 복잡도를 생각해보면, 최대 50글자이다.
list나 string을 사용해서 중간에 insert를 해도 됨!


최근 코드

: 짝수일 때랑 홀수일때를 구별해야 할 것 같다고 생각함.

  • 코드
#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>
#include <string>


int main()
{
	string word;
	cin >> word;

	// levvel 
	// level 

	// 짝수일 때와 홀수일 때를 구별해야 함. 

	int n = word.length() / 2; 

	int bbegin = 0;
	int eend = word.length() - 1;

	while (n--)
	{
		if (word[bbegin++] == word[eend--])
		{

		}
		else
		{
			cout << 0;
			return 0;
		}
	}
	cout << 1;
	return 0;
}

풀이 전략 1번

: 앞 , 뒤 를 확인 후 같으면 앞, 뒤 제거
=> 덱으로 접근함.
같지 않으면? -> 0으로 리턴이고,

  • 추가적인 조건으로는 level 과 같이 가운데 값이 하나일 경우,
    -> 조건 추가해야 함.

1번 코드

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#include <algorithm>
#include <vector>
#include <deque>

int main()
{
	
	string s;
	cin >> s;

	deque<char>d(s.length());

	for (int i = 0; i < s.length(); i++)
	{
		d[i] = s[i];
	}

	while (!d.empty())
	{
		char start = d.front();
		char end = d.back();

		if (start == end)
		{
			d.pop_front();
			if(!d.empty())
				d.pop_back();
		}
		else
		{
			cout << 0;
			break;
		}
	}
	
	if (d.empty())
		cout << 1;
}

풀이 전략 2번.

: 원본 문자열과 , 뒤집은 문자열을 비교하는 방법이 있음.

-> 원본 : level / 뒤집으면 : level : 비교하면 -> ok
-> 원본 : zzokki / 뒤집으면 : ikkozz : 비교하면 -> no!

  • 뒤집어주는 함수가 있음.

2번 코드

#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#include <algorithm>
#include <vector>
#include <deque>

int main()
{
	string s1;
	cin >> s1;

	string s2{ s1 };
	reverse(s2.begin(), s2.end());

	if (s1 == s2)
		cout << 1;
	else
		cout << 0;
	
}

profile
🔥🔥🔥

0개의 댓글

관련 채용 정보