카테고리 없음
C++ 1259 팰린드롬수
jjiing
2022. 6. 30. 14:48
벡터로 string 배열을 받아준다.
(굳이 배열로 안받아주고 cin 할때마다 검사해줘도 된다)
for문으로 단어 사이즈/2만큼 반복을 돌려서
단어의 첫글자, 마지막글자 같은지 검사.
bool값으로 앞뒤글자 달라지면 false로 바뀌게끔 해서 풀었다.
자꾸 답은 나오는데 틀렸다고 나오길래 씨름하다가
bool 값 초기화 위치를 바꿔주니 정답이다.
근데 이 문제는 이렇게 푸는 것 보다
reverse 함수로 풀어주는게 훨씬 훨~씬 간단하다,,ㅠㅠ
밑에 reverse 풀이도 넣어둔다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
bool result = true;
while (1)
{
string word;
cin >> word;
if (word == "0") break;
words.push_back(word);
}
for(int i = 0 ; i<words.size();i++)
{
result = true; //초기화
for (int j = 0; j < words[i].size() / 2; j++)
{
if (words[i][j] != words[i][words[i].size() - 1 - j])
result = false;
}
if (result) cout << "yes"<<endl;
else cout << "no" << endl;
}
}
reverse풀이
reverse(word.begin(), word.end()); 를 사용하면 string 배열이 뒤집힌다.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
while (1)
{
string word;
cin >> word;
if (word == "0") break;
string temp = word;
reverse(word.begin(), word.end());
if (temp == word)
cout << "yes" << endl;
else
cout << "no" << endl;
}
}