Leetcode/Top Interview 150

[Two Pointers][Easy] 125. Valid Palindrome

자전거통학 2024. 5. 3. 02:48

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

 

Q. 문자열 s 가 주어질 때, 문자와 숫자에 대해 palindrome한지 확인 하라. 

 

 

Solution. 

 Palindrome check를 대상 문자일 때 수행한다. 

 

 코드. 

 

bool isAlphabet(char cur)
{
    if(cur>='A' && cur<='Z')
        return true;
    if(cur>='a' && cur<='z')
        return true;
    if(cur>='0' && cur<='9')
        return true;
    return false;
}
public bool IsPalindrome(string s) 
{    
    int left = 0;
    int right = s.Length-1;

    while(left<s.Length && right>=0 && left<right)
    {
        while(left<s.Length && !isAlphabet(s[left]))
            ++left;
        while(right>=0 && !isAlphabet(s[right]))
            --right;

        if(left<s.Length && right>=0 && char.ToLower(s[left++])!=char.ToLower(s[right--]))
            return false;
    }
    return true;
}

 

결과.