Longest Palindromic Substring in Bash
This document provides a Bash script to find the longest palindromic substring in a given string. While Bash is not the most efficient language for this task, the script demonstrates how string manipulations can be performed in Bash.
Program Explanation
The script performs the following steps:
- Initialization: It initializes variables for the input string, the length of the string, and the longest palindrome found.
- Check for Palindrome: The script uses a nested loop to check all substrings of the input string to determine if they are palindromes.
- Update Longest Palindrome: If a longer palindrome is found, it updates the longest palindrome variable.
- Output Result: Finally, it prints the longest palindromic substring.
Bash Script
#!/bin/bash
# Function to check if a given substring is a palindrome
is_palindrome() {
local str="$1"
local len=${#str}
for (( i=0; i<$((len/2)); i++ )); do
if [ "${str:i:1}" != "${str:len-i-1:1}" ]; then
echo "false"
return
fi
done
echo "true"
}
# Function to find the longest palindromic substring
longest_palindromic_substring() {
local input="$1"
local length=${#input}
local longest=""
for (( start=0; start<$length; start++ )); do
for (( end=$start+1; end<=$length; end++ )); do
substring="${input:start:end-start}"
if [ "$(is_palindrome "$substring")" == "true" ] && [ ${#substring} -gt ${#longest} ]; then
longest="$substring"
fi
done
done
echo "$longest"
}
# Main script execution
if [ "$#" -ne 1 ]; then
echo "Usage: $0 'string'"
exit 1
fi
input_string="$1"
result=$(longest_palindromic_substring "$input_string")
echo "Longest Palindromic Substring: $result"
How to Run the Script
To run the script:
- Save the script to a file, e.g.,
longest_palindrome.sh
. - Make the script executable by running:
chmod +x longest_palindrome.sh
- Execute the script with a string argument:
./longest_palindrome.sh "yourstring"
Example
If you run the script with the string "babad"
, the output will be:
Longest Palindromic Substring: aba
Explanation
- Initialization: The script starts by defining a function to check if a substring is a palindrome. It also defines another function to find the longest palindromic substring by iterating over all possible substrings.
- Check for Palindrome: The
is_palindrome
function checks if a given string reads the same forwards and backwards. - Update Longest Palindrome: The
longest_palindromic_substring
function finds all substrings of the input string and keeps track of the longest palindromic substring. - Output Result: The script prints the longest palindromic substring found.
Remember, while this script demonstrates the concept, Bash is not the most efficient for such tasks, and other languages like Python or JavaScript might be more suitable for more extensive or performance-critical applications.