checking if a string is a palindrome

后端 未结 4 463
难免孤独
难免孤独 2021-01-14 19:40

I am trying to check if a string is a palindrome in bash. Here is what I came up with:

#!/bin/bash
read -p \"Enter a string: \" string
if [[ $string|rev ==         


        
4条回答
  •  青春惊慌失措
    2021-01-14 20:22

    A bash-only implementation:

    is_palindrome () { 
        local word=$1
        local len=$((${#word} - 1))
        local i
        for ((i=0; i <= (len/2); i++)); do
            [[ ${word:i:1} == ${word:len-i:1} ]] || return 1
        done
        return 0
    }
    
    for word in hello kayak; do
        if is_palindrome $word; then
            echo $word is a palindrome
        else
            echo $word is NOT a palindrome
        fi
    done
    

    Inspired by gniourf_gniourf:

    is_palindrome() {
      (( ${#1} <= 1 )) && return 0
      [[ ${1:0:1} != ${1: -1} ]] && return 1
      is_palindrome ${1:1: 1}
    }
    

    I bet the performance of this truly recursive call really sucks.

提交回复
热议问题