Valid Palindrome

Yohan Kim·2021년 9월 8일
0

problem

주어진 문장이 palindrome 인지 검사하는 함수입니다.
palindrome -> 문장의 순서를 뒤집어도 똑같은 문장인 것.

ex) 기러기, race a car

solution

// probem no : 125
class Solution {
public:
    bool isPalindrome(string s) {
        int start = 0, end = s.size()-1;
        while(start < end){
            if(!isalnum(s[start])){ 
                start++;
                continue;
            }
            if(!isalnum(s[end])){
                end--;
                continue;
            }
            if(tolower(s[start]) != tolower(s[end])){
                return false;
            }
            else{
                start++;
                end--;
            }
        }
        return true;
        
    }
};

후기

스트링을 전처리하는 것이 관건이였던 문제인 것 같습니다.

string의 기본적인 구조 (char의 배열) 임을 이용해서 palindrome을 검사하는 것은 간단히 할 수 있지만,

alpanumaric이 아닌 나머지 char들을 어떻게 처리하느냐가 관건이었던 문제입니다.

조금 찾아보니까 <ctype.h>의 isalnum() , tolower()을 사용해서 쉽게 구현할 수 있었습니다.

다른 출제자의 코드에서는 isalnum() 대신

bool isalnum(char c){
	if(('a' <= c && c <='Z') || ('1'<=c && c<='9')){
    		return true;
  	}else{ return false; }
}

이런 식으로 직접 함수를 만들어서 쓰는 코드도 이었습니다.

profile
안녕하세요 반가워요!

0개의 댓글