zoukankan      html  css  js  c++  java
  • shell脚本实现检測回文字符串

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

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

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

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

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

    '(.)(.)21'

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

    #!/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


  • 相关阅读:
    第四次作业
    团队编程第三次博客
    团队编程2
    团队编程
    ARM寄存器总结:
    proc介绍及问题分析
    Ubuntu连接手机步骤
    Bluetooth(android 4.2.2版本)
    Android Bluetooth 总结
    android代码常识
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5347131.html
Copyright © 2011-2022 走看看