IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]【字符串处理算法】回文判断的算法设计及C代码实现

    zhouzxi发表于 2016-02-22 17:41:14
    love 0

    一、需求描述

    输入一个字符串,编写程序判断这个字符串是否是回文串。


    为了便于说明,设定输入的字符串分为中文字符串和非中文字符串两种。其中,中文字符串中仅包含中文字符,非中文字符串中不包含中文字符。


    所谓回文串,是指正读和反读都一样的字符串。下面举几个例子予以说明:

    1.“level”是一个非中文字符的回文串,因为正读和反读都是“level”。


    2.“Good”不是一个非中文字符的回文串。


    3.“我爱我”是一个中文字符的回文串,因为正读和反读都是“我爱我”。


    4.“我爱你”不是一个中文字符的回文串。

     

    二、算法设计

    对于非中文字符的回文串的判断比较简单,我们只要以字符串的中间为原点,比较前后对应的字符是否相等就可以了;但对于中文字符的回文串的判断要复杂一点,因为一个中文字符占两个字节,我们不能采用非中文字符的回文串的判断方法,而是应该先单独获取每个中文字符,然后再比较一前一后两个字符是否相等。


    程序的总体流程如图1所示。

    图1 程序的总体流程

     

    三、特殊流程考虑

    在编写程序的过程中,我们要对输入的字符串的长度及格式多做考虑,如:

    1.如果输入的字符串中只有一个字符,那么程序直接返回,不执行后续流程,因为回文串中至少有两个及以上的字符。


    2.如果输入的中文串中含有非中文字符,或者是输入的非中文串中含有中文字符,那么程序直接返回,不执行后续流程。

     

    四、程序代码

     

    {CSDN:CODE:1584947}

     

    五、程序测试

    我们将编写好的程序“PalindromicString.c”上传到Linux机器,并使用“gcc -g -o PalindromicStringPalindromicString.c”命令对该程序进行编译,生成“PalindromicString”文件。下面对程序进行详细的测试。


    1.输入中文字符串为“人上人”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    1

    Please input the string:

    人上人

    人上人 is a palindromic string!

     

    2.输入中文字符串为“我是谁”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    1

    Please input the string:

    我是谁

    我是谁 is not a palindromic string!

     

    3.输入非中文字符串为“level”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    2

    Please input the string:

    level

    level is a palindromic string!

     

    4.输入非中文字符串为“good”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    2

    Please input the string:

    good

    good is not a palindromic string!

     

    5.输入字符串为“你好good”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    1

    Please input the string:

    你好good

    你好good has non-Chinese character, pleasecheck!

     

    6.输入字符串为“good好”时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    2

    Please input the string:

    good好

    good好 has Chinese character, pleasecheck!

     

    7.输入字符串类型非1或2时,程序运行情况如下:

    Please input the string type(1:中文字符串,2:非中文字符串):

    3

    Please input the string:

    goog

    Please input the right string type!

     

    可见,对于上面考虑到的几种特殊情况,程序均能做出正确的处理。

     

    六、需求扩展

    基于本文中的需求和程序,我们可考虑对需求进行以下扩展:

    1.不限制输入的字符串中只能是中文串或者非中文串,可以是中文字符和非中文字符的混合串。


    2.当输入的字符串中是非中文串时,要求该字符串的字符个数为偶数。即要求形如“goog”这样的字符串为回文串,而像“level” 这样的字符串不为回文串。

     



沪ICP备19023445号-2号
友情链接