5. Longest Palindromic Substring

背景

“回文”是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如“我为人人,人人为我”等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。

设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。
注意:
1. 偶数个的数字也有回文数124421
2. 小数没有回文数

题目

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: “babad”

Output: “bab”

Note: “aba” is also a valid answer.

Example:

Input: “cbbd”

Output: “bb”

代码实现

public string LongestPalindrome(string s)
        {
            //considering: adccbaabc. we get the palindrome "cc" and "cbaabc"
            //How do we get the "cbaabc"? 
            //first k points to second 'a' and j points to first 'b'  by such logics: 
            //while (k < s.Length - 1 && s[k + 1] == s[k])
            //    ++k; // moves when happing duplicate characters.

            //then we compare the k+1 index to j-1 index, such s[k+1]== s[j-1] is ok. It's finished by expand logics:
            //while (k < s.Length - 1 && j >= 1 && s[k + 1] == s[j - 1])
            //{
            //    ++k;
            //    --j;
            //}
            if (s.Length== 0 || s.Length==1) return s;
            int i=0, minstart = 0, maxlen = 1;
            while(i<s.Length){
                if (s.Length - i <= maxlen / 2) break;
                int j = i, k = i;
                while (k < s.Length - 1 && s[k + 1] == s[k]) 
                    ++k; 
                i = k + 1;
                while (k < s.Length - 1 && j >= 1 && s[k + 1] == s[j - 1]) {
                    ++k;
                    --j;
                }
                int newlen = k - j + 1;
                if (newlen > maxlen){
                    minstart = j;
                    maxlen = newlen;
                }
            }
            return s.Substring(minstart, maxlen);
        }

题库

Leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

完成题目索引

http://blog.csdn.net/daigualu/article/details/73008186

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值