125 Valid Palindrome· LeetCode Solutions.

Problem

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:Input: s = “A man, a plan, a canal: Panama” Output: true Explanation: “amanaplanacanalpanama” is a palindrome.

Example 2:Input: s = “race a car” Output: false Explanation: “raceacar” is not a palindrome.

Example 3:Input: s = ” ” Output: true Explanation: s is an empty string “” after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

Process to solve Valid Palindrome problem

  • To solve Valid Palindrome problem first create a regex pattern that will check for all alphabets and numbers.
  • Create a variable to store filtered value and Replace the given string with the empty character if it doesn’t exist in the pattern that we created.
  • Convert our filteredText into lowercase.
  • Create two variables to store the index of our start position and end position.
  • Now we will check the first character of our filteredText and last character of our filteredText.
  • if it is the same we will increase the pointer of the start variable and decrease the pointer of the end variable.
  • If it is false, we will return false.
  • If we complete the loop successfully, we will return true.

Solution

using System.Text.RegularExpressions;
public class Solution {
    public bool IsPalindrome(string s) {
        string pattern = "[^a-zA-Z0-9]";
        string filteredText = Regex.Replace(s, pattern, "");
        filteredText = filteredText.ToLower();
        int start = 0;
        int end = filteredText.Length - 1;
        while(end > start){
            if(filteredText[end] != filteredText[start]){
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *