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

思想

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

判断是否回文字符串

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

结果

decocdeui

源码

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

相关文章
相关标签/搜索