基础算法----判断回文

思想

我的实现比较简单就是两个指针一头一尾,对比两个值是否相等,如果题目改变:寻找最大回文,方法同样适用,修改起始索引即可;

判断是否回文字符串

string huiwen = "abcdcba";

#region 判断回文
static void checkHuiWen(string str)
{
    bool result = true;
    char[] arr = str.ToArray();
            /**
            * 回文对比中心索引两边值,依次做比较;
            * */
    int index = arr.Length - 1 / 2;
    int end = arr.Length - 1;
    for (int i = 0; i < index; i++)
    {
        if (arr[i] != arr[end - i])
        {
            result = false;
            break;
         }
    }
    if (result)
        System.Console.Write("say yes");
    else
        System.Console.Write("say no");
}
#endregion

输出

say yes;

寻找最大回文字符串

string huiwen = "abcdedcocde";

#region 最大回文字符串
static void maxHuiWenString(string str)
{
     char[] arr = str.ToArray();
     string tempStr = "";
     string result = "";
            /**
            * 以数组每个数字为中心,前后比较,如果前值等于后值则记录;
            * 循环体结束之后,进行多个回文比较,长度最大的保留;
            * */
    for (int i = 0; i < arr.Length; i++)
     {
           for (int j = 1; j <= i; j++)
            {
                if ((i - j) > 0 && (i + j) < arr.Length && arr[i - j] == arr[i + j])
                {
                    if (tempStr == "")
                        tempStr = arr[i].ToString();
                    tempStr = arr[i - j] + tempStr + arr[i + j];
                }
                else
                    break;
            }
            if (tempStr.Length >= result.Length)
            {
                result = tempStr;
                tempStr = "";
            }
        }
        System.Console.WriteLine(result);
    }
#endregion

结果

decocde

源码

http://git.oschina.net/aspnet/Suan-Fa

转载于:https://my.oschina.net/u/1000241/blog/847001

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值