[One question per day] 18: Verify the palindrome

Title description

Given a string, verify that it is a palindrome string, considering only alphabetic and numeric characters, you can ignore the case of letters.

Explanation: In this question, we define an empty string as a valid palindrome string.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false

Ideas:

  1. Traverse the string from the beginning and end of the string at the same time

  2. First determine whether the character at this position of the string is an alphanumeric character (write a function)

  3. If it is, then save the subscript and jump out of the loop (in this process, upper and lower case letters are arranged uniformly); otherwise, skip this character and detect the next character

  4. Determine whether the string is a palindrome by comparing the characters corresponding to the subscripts before and after

code show as below:

bool IsNumber(char c){
    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

class Solution {
public:
    bool isPalindrome(string s) {
        if(s.empty())
            return true;

        int start = 0;
        int end = s.size() - 1;

        while(start < end){
            while(start != end){
                if(IsNumber(s[start])){
                    if((s[start] >= 'A' && s[start] <= 'Z')){
                        s[start] += 32;
                    }
                    break;
                }
                    
                ++start;
            }

            while(start != end){
                if(IsNumber(s[end])){
                    if((s[end] >= 'A' && s[end] <= 'Z')){
                        s[end] += 32;
                    }
                    break;
                }
                
                --end;
            }

            if(s[start] == s[end]){
                ++start;
                --end;
            }
            else{
                return false;
            }
        }
        return true;
    }
};

//验证代码
int main() {
    Solution S;
    string str;
    getline(cin, str);
    if(S.isPalindrome(str))
        cout << "true" << endl;
    else
        cout << "false" << endl;

    return 0;
}

Code generation diagram
Insert picture description here


If you have different opinions, please leave a message to discuss ~

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105047183