[백준] 1259번. Palindrome Numbers

leeeha·2021년 9월 19일
0

백준

목록 보기
2/185

https://www.acmicpc.net/problem/1259

먼저 std::reverse 함수에 대해 알아보자!

https://blockdmask.tistory.com/363

template <class BidirectionalIterator>
void reverse(BidirectionalIterator first, BidirectionalIterator last) {
    while ((first != last) && first != --last) {
        std::iter_swap(first++, last);
    }
}

reverse 함수는 양방향 반복자를 사용할 수 있는 컨테이너라면 무엇이든 그 순서를 뒤집을 수 있다. string은 물론이고, vector, list도 모두 가능!

#include <iostream>
#include <algorithm> // std::reverse
#include <vector>
using namespace std;

void printVector(const vector<int>& v) {
    for (auto& val : v)
        cout << val << " ";
    cout << endl;
}

int main(void) 
{
    // string 뒤집기
    string str = "BlockDMask";
    cout << "Before : " << str << endl; // "BlockDMask"
    reverse(str.begin(), str.end());
    cout << "After  : " << str << endl; // "ksaMDkcolB"
    
    // vector 뒤집기
    vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    cout << "Before : ";
    printVector(v);
    reverse(v.begin(), v.end());
    cout << "After  : ";
    printVector(v);

    return 0;
}

내 풀이: std::reverse 이용

#include <iostream>
#include <algorithm> // std::reverse
using namespace std;

int main() 
{
	string str;
	while (true) {
		cin >> str;

		// 입력이 0이면 루프 종료
		if (str == "0") break;

		// 원본 문자열 임시 저장
		string tmp = str;

		// 문자열 뒤집기
		reverse(str.begin(), str.end());

		// 문자열 비교
		// if(tmp == str) ...
		if (tmp.compare(str) == 0) cout << "yes\n";
		else cout << "no\n";
	}

	return 0;
}

다른 풀이: isPalindrome 함수 구현

https://yjyoon-dev.github.io/boj/2021/06/22/boj-1259/

#include <iostream>
using namespace std;

bool isPalindrome(string& s) {
	int left = 0, right = s.size() - 1;
	while (left < right) {
		if (s[left++] != s[right--])
			return false;
	}
	return true;
}

int main() {
	string str;
	while (true) {
		cin >> str;
		if (str == "0") break;

		if (isPalindrome(str)) cout << "yes\n";
		else cout << "no\n";
	}
}
profile
Keep Going!

0개의 댓글