题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param A string字符串
     * @return int整型
     */
    public int getLongestPalindrome (String str) {
        if (str.length() <= 1) {
            return str.length();
        }
        int start = 0, maxLen = 1;

        for (int index = 0; index < str.length(); index++) {
            int left = index - 1, right = index + 1, curLen = 1;
            while (left >= 0 && str.charAt(left) == str.charAt(index)) {
                left--;
                curLen++;
            }
            while (right < str.length() && str.charAt(right) == str.charAt(index)) {
                right++;
                curLen++;
            }
            while (left >= 0 && right < str.length() &&
                    str.charAt(left) == str.charAt(right)) {
                right++;
                left--;
                curLen += 2;
            }
            if (curLen > maxLen) {
                start = left;
                maxLen = curLen;
            }
        }
        return maxLen;
    }
}

全部评论

相关推荐

05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
无实习如何秋招上岸
点赞 评论 收藏
分享
06-19 19:06
门头沟学院 Java
码农索隆:别去东软,真学不到东西,真事
点赞 评论 收藏
分享
07-16 14:10
门头沟学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务