shell脚本实现检測回文字符串

it2025-06-09  26

全部回文字的结构特征例如以下:

假设字符数是偶数,那么它在结构上表现为:一个字符序列连着还有一个字符同样但次序恰好相反的字符序列。

假设字符数为奇数,那么它在结构上表现为:一个字符序列连着还有一个字符同样但次序恰好相反的字符序列,可是这两个序列中间共享一个同样的字符。

sed命令可以记住之前匹配的子样式。

可以用正則表達式:'\(.\)'。匹配随意一个字符。\1表示其反向引用。如匹配有两个字符的回文正則表達式为:

'\(.\)\(.\)\2\1'

匹配随意长度的回文脚本例如以下所看到的:

#!/bin/bash #file name: match_palindrome.sh #function: find palindrome in a file. if [ $# -ne 2 ] then echo "Usage: $0 filename string_length" exit -1 fi filename=$1 basepattern='/^\(.\)' count=$(( $2/2 )) # matche certain length for ((i=1; i < $count; i++)) do basepattern=$basepattern'\(.\)'; done # the length is even if [ $(( $2 % 2)) -ne 0 ] then basepattern=$basepattern'.'; fi for ((count; count > 0; count--)) do basepattern=$basepattern'\'"$count"; done echo "debug: $basepattern" # print the result basepattern=$basepattern'$/p' sed -n "$basepattern" $filename

转载于:https://www.cnblogs.com/bhlsheji/p/5347131.html

相关资源:数据结构—成绩单生成器
最新回复(0)