Leetcode - 125. Valid Palindrome

숲사람·2022년 6월 27일
0

멘타트 훈련

목록 보기
74/237

문제

주어진 문자열이 Palindrome(좌우에서 읽어도 동일)인지 확인

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

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

Useful components

  • 알파벳을 문자열을 모두 소문자로 바꾸기
    std::tolower() 사용. 한 char를 변환가능.
        for (auto &c: s)
            c = std::tolower(c);
  • string 문자열에 문자 추가 업데이트
    초기에 문자열 크기를 지정할 필요없이 push_back() 하면 됨.
converted_s.push_back(std::tolower(c));
  • Pailindrome 체크 루틴 (양끝에서 가운데로)
        while (left < right) {
            if (new_s[left++] != new_s[right--])
                return false;
        }

해결 O(N)

#include <string>
class Solution {
public:
    string nomalize_str(string s) {
        std::string converted_s;
        for (auto c: s) {
            if ((c >= 'A' && c <= 'Z') || 
                (c >= 'a' && c <= 'z') || 
                (c >= '0' && c <= '9'))
                converted_s.push_back(std::tolower(c));
            else
                continue;
        }
        return converted_s;
    }
    
    bool isPalindrome(string s) {
        string new_s = nomalize_str(s);
        int left = 0;
        int right = new_s.size() - 1;
        while (left < right) {
            if (new_s[left++] != new_s[right--])
                return false;
        }
        return true;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글