Palindrome
Definition​
- Definition
- Explanation
- Guidance
- Tips
The Palindrome Algorithm is a method used to determine whether a given input string reads the same forwards and backwards. It utilizes string manipulation techniques to compare characters from both ends of the string simultaneously
It works by comparing characters from the beginning and end of the input string. It iterates through the string, starting from both ends and moving towards the center simultaneously. At each step, it compares the characters at these positions. If all characters match, the string is a palindrome. If any characters don't match, the string is not a palindrome. The algorithm terminates when the pointers meet at the center of the string or cross each other
- Start with two pointers, one at the beginning and one at the end of the string
- compare characters at these pointers
- if they match, move both pointers towards the center of the string
- if they don't match, the string is not a palindrome
- repeat steps until the pointers meet at the center or cross each other
- If the pointers meet without any mismatch, the string is a palindrome
- avoid unnecessary operations that may increase the time complexity
- consider edge cases such as empty strings or strings with a single character
Practice​
- Practice
- Solution
isPalindrome(string):
// Initialize pointers
leftPointer = 0
rightPointer = length(string) - 1
// Loop until pointers meet or cross
while leftPointer < rightPointer:
// Compare characters at pointers
if string[leftPointer] != string[rightPointer]:
return false // Not a palindrome
// Move pointers towards center
leftPointer += 1
rightPointer -= 1
return true // Palindrome
package main
import (
"strings"
)
func isPalindrome(s string) bool {
s = strings.ToLower(s)
i, j := 0, len(s)-1
for i < j {
if s[i] != s[j] {
return false
}
i++
j--
}
return true
}
function isPalindrome(s) {
s = s.toLowerCase();
let i = 0, j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) {
return false;
}
i++;
j--;
}
return true;
}
function isPalindrome(s) {
s = s.toLowerCase();
let i = 0,
j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) {
return false;
}
i++;
j--;
}
return true;
}
fun isPalindrome(s: String): Boolean {
var i = 0
var j = s.length - 1
val str = s.toLowerCase()
while (i < j) {
if (str[i] != str[j]) {
return false
}
i++
j--
}
return true
}
def is_palindrome(s):
s = s.lower()
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
fn is_palindrome(s: &str) -> bool {
let s = s.to_lowercase();
let mut i = 0;
let mut j = s.len() - 1;
while i < j {
if s.chars().nth(i).unwrap() != s.chars().nth(j).unwrap() {
return false;
}
i += 1;
j -= 1;
}
true
}
function isPalindrome(s: string): boolean {
s = s.toLowerCase();
let i = 0,
j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) {
return false;
}
i++;
j--;
}
return true;
}