반응형
어떤 단어를 뒤에서부터 읽어도 똑같다면 그 단어를 팰린드롬이라고 한다. 'radar', 'sees'는 팰린드롬이다.
팰린드롬수 판단 문제.
전체 문자열의 절반 기준으로 잘라서 앞과 뒤를 비교해줬다.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
int i;
while(1) {
cin >> str;
if(str[0] == '0')
return 0;
for(i = 0; i < (str.length() / 2); i++) {
if(str[i] != str[str.length() - 1 - i]) {
break;
}
}
if(i == str.length() / 2)
cout << "yes\n";
else
cout << "no\n";
}
}
그리고 C++ <algorithm> 에 reverse 함수가 있다고 해서 이를 이용해서 다시 풀어보았다.
#include <iostream>
#include <string>
#include <algorithm> // reverse함수 존재
using namespace std;
int main() {
string str;
string temp;
while(1) {
cin >> str;
if(str[0] == '0')
return 0;
temp = str;
reverse(temp.begin(), temp.end());
if(!str.compare(temp)) // 같다면(char의 strcmp와 동일)
cout << "yes\n";
else
cout << "no\n";
}
}
그리고 JAVA로도 풀어보았는데, JAVA에서는 String에 문자열의 끝을 나타내는 '\0' 문자에 대한 개념이 있던가.. 가물가물하다.
(C언어는 참고로 있다. char[]에서.. )
받아온 String을 뒤집어서 캐릭터형식으로 하나하나 복사하는데도 compareTo함수로 두 문자열이 같다고 판단된다.
아마 String에 '\0' 개념이 없거나 compareTo 가 '\0' 기준을 잡지 않거나. 둘중하나인듯하다.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class baekjoon {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (true) {
String str = br.readLine(); // == String str = new String(br.readLine());
if(str.charAt(0)=='0')
return;
String s = "";
for (int i = str.length() - 1; i >= 0; i--)
s += str.charAt(i);
if(str.compareTo(s) == 0)
bw.write("yes\n");
else
bw.write("no\n");
bw.flush();
}
}
}
반응형
'[알고리즘 + 자료구조] > [백준]' 카테고리의 다른 글
[BaekJoon/백준] 10816번 C++ (0) | 2021.03.21 |
---|---|
[BaekJoon/백준] 1920번 C++ (0) | 2021.03.20 |
[BaekJoon/백준] 2920번 C++/JAVA (0) | 2021.03.19 |
[BaekJoon/백준] 11444번 분할정복 (0) | 2021.03.19 |
[BaekJoon/백준] 10830번 분할정복 (0) | 2021.03.18 |