Valid palindrome
Original title link valid palindrome
To determine if a given string is a palindrome, just compare the ASCII code letters and numbers, and the other symbols skip
First, we introduce two functions, it is convenient to use int isalnum (int c), if C is a number or uppercase letter, return true int toupper (int c); Convert character C to uppercase
The palindrome string is symmetrical, so it only needs to be judged from both sides to the middle.
The code is as follows
Class Solution {public
:
bool Ispalindrome (string s) {
int n = s.size ();
int front = 0, back = n-1;
while (front < back)
{
while (front < n &&!isalnum (S[front]))
++front;
while (Back > Front &&!isalnum (S[back]))
--back;
if (Back > Front && toupper (S[front])! = ToUpper (S[back]))
return false;
++front;
--back;
}
return true;
}
};
Valid palindrome II
Original title link valid palindrome II
Allows a maximum of one character to be removed to determine whether a given string can be changed to a palindrome, with lowercase letters in the string
In the same way, is still pushed from both sides, if you encounter a mismatched character, then allow the deletion of a character, then there are two possible, one is to delete the left character, the other is to delete the right character
Recursive methods can be used, and because only one character is deleted, the recursive depth does not exceed 1
The code is as follows
Class Solution {public
:
bool Validpalindrome (string s) {
int n = s.size ();
Return Ispalindrome (S, 0, n-1, 0);
}
Private:
bool Ispalindrome (string& s, int start, int end, int count)
{
if (Start > End)
return Fals e;
if (start = = end)
return true;
while (Start < end)
{/
* If not equal, remove one of the characters, recursively, and note that it can only be deleted once so you need to determine if count is 0 *
/if (S[start]! = S[end])
{
return!count && (Ispalindrome (S, start, end-1, Count + 1) | | Ispalindrome (S, start + 1, end, Count + 1));
}
else
{
++start;
--end;
}
}
return true;
}
};
For recursive strings, it is better to judge from the left and right sides to the middle. In addition to the topic of strings, there is a search for the longest recursive substring in the string, with each position centered toward each side looking for the longest palindrome substring starting from the first character of the string, using KMP's prefix array to solve