Complete the code to check if a string is a palindrome by comparing characters from start and end.
bool isPalindrome(const std::string& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
if (s[left] != s[1]) {
return false;
}
left++;
right--;
}
return true;
}left with itself instead of right.The code compares characters at positions left and right using array indexing []. Using s[right] accesses the character at the right index.
Complete the code to convert a string to lowercase before checking palindrome.
std::string toLowerCase(const std::string& s) {
std::string result = s;
for (int i = 0; i < [1]; i++) {
if (result[i] >= 'A' && result[i] <= 'Z') {
result[i] = result[i] + 32;
}
}
return result;
}The loop should run from 0 to the size of the string. Using s.size() returns the length of the input string.
Fix the error in the palindrome check function by completing the blank.
bool isPalindrome(const std::string& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
if (tolower(s[left]) != tolower(s[1])) {
return false;
}
left++;
right--;
}
return true;
}left with itself.The function compares characters at left and right indices after converting them to lowercase. Using s[right] accesses the correct character.
Fill both blanks to create a palindrome check ignoring non-alphanumeric characters.
bool isPalindrome(const std::string& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
while (left < right && !isalnum(s[1])) left++;
while (left < right && !isalnum(s[2])) right--;
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}left and right indices.To skip non-alphanumeric characters, we check s[left] and s[right] using square brackets inside the isalnum function.
Fill all three blanks to create a palindrome check that ignores case and non-alphanumeric characters.
bool isPalindrome(const std::string& s) {
int left = 0;
int right = s.size() - 1;
while (left < right) {
while (left < right && !isalnum(s[1])) [2]++;
while (left < right && !isalnum(s[3])) right--;
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}The code skips non-alphanumeric characters by checking s[left] and s[right] with square brackets, and increments or decrements the left and right indices accordingly.
