[Primary Algorithm] 16. Validate the palindrome string

topic:

Given a string, verify that it is a palindrome, considering only alphanumeric characters, ignoring case of letters.

Explanation: In this problem, we define the empty string as a valid palindrome.

Example 1 :

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

Input: " race a car " 
Output: false

1. Problem solving ideas:

This question is relatively simple, directly compare the front and rear letters of the string, if they are equal, move forward, otherwise return an error.

 

class Solution {
public:
    bool isPalindrome(string s) {
        int len = s.size();
        int start = 0;
        int end = len-1;
        
        while(start < end){
            char first,second;
            /*get the fisrt char*/
            while(start <= end){
                if((s[start] >= 'a' && s[start] <= 'z')||
                   (s[start] >= 'A' && s[start] <= 'Z')||
                   (s[start] >= '0' && s[start] <= '9')){
                    first = s[start];
                    if(s[start] >= 'A' && s[start] <= 'Z'){
                        first = first-'A'+'a';
                    }
                    break;
                }else{
                    start++;
                }
            }
            
            /*get the second char*/
            while(start <= end){
                if((s[end] >= 'a' && s[end] <= 'z')||
                   (s[end] >= 'A' && s[end] <= 'Z')||
                   (s[end] >= '0' && s[end] <= '9')){
                    second = s[end];
                    if(second <= 'Z'&&second>='A'){
                        second = second-'A'+'a';
                    }
                    break;
                }else{
                    end--;
                }
            }
            
            if(start > end){
                break;
            }
            
            if(first == second){
                start++;
                end--;
            }else{
                return false;
            }
        }
        
        return true;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325260388&siteId=291194637