7.Valid Palindrome

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

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

Input: "race a car"
Output: false

Solution:-

class Solution {
public:
    bool isPalindrome(string s) {
        
        if(s==""){return true;}
        
       int start = 0;
       int end = s.length()-1;
        bool res = true;
       while(start<=end){
           
           int x = tolower(s[start]);
           int y = tolower(s[end]);
           if(x<97||x>122){
               if(x<48||x>57){
               start++;
               continue;
             }
           }
           
            if(y<97||y>122){
              if(y<48||y>57){
                end--;
                continue;
           }
          }
           
           if(x!=y){
                res = false;
                 break;
            }
    
           start++;
           end--;
       }
        
    return res;
    }
};

Time Complexity :- O(n)

Valid Palindrome II:

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Solution:

Algorithm: We will be comparing char from start and end. If there is a mismatch. Then we can make one deletion We will make one deletion and check and if the rest is string is palindrome.

Last updated

Was this helpful?