본문 바로가기

풀어본 Algorithm 문제 정리

[OJ.leetcode] Valid Palindrome

https://oj.leetcode.com/problems/valid-palindrome/


Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.


//empty string = valid

//extra memory = none

//only alphabet case

//solution : two runner(head, end) 끝에서부터 서로 비교하면서 만날때까지 증감.

//time complexity : O(2n)

//test case : "", "   ", "a", "aba", "abcba", "a a baa", "a b c d  e"

        

class Solution {

public:

    bool isPalindrome(string s) {

        if(s.length() <= 1) return true;

           

        transform(s.begin(), s.end(), s.begin(),::tolower);

        std::string::iterator head = s.begin();

        std::string::iterator tail = s.end();

        tail--;

        

        while(head < tail) {

          while( !((*head >= '0' && *head <= '9') || (*head >= 'a' && *head <= 'z')) && (head < tail) ) {

               head++;

          }


          while( !((*tail >= '0' && *tail <= '9') || (*tail >= 'a' && *tail <= 'z')) && (head < tail) ) {

               tail--;

          }

          

          if(*head != *tail) return false;

          else {

              head++;

              tail--;

          }

        }

        

        return true;

    }