zoukankan      html  css  js  c++  java
  • 【leetcode】5. Longest Palindromic Substring

    题目描述:

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

    解题分析:

        之前百度实习生面试也被问到这个问题。这个题比较简单。就是在分别考虑对称字符字串为奇数和偶数的情况,在不超过字符串范围的情况下向两边扩展,找到最大值,并记录下最大子串的位置,最后返回即可。

    具体代码:

    public class Solution {
        public static String longestPalindrome(String s) {
            if(s==null)
                return null;
            if(s.length()==0)
                return "";
            if(s.length()==1)
                return s;
            if(s.length()==2){
                if(s.charAt(0)!=s.charAt(1)){
                    return s.substring(1);
                }
                else
                    return s;
            }
            int max=1;
            int start=0;
            int end=0;
            char[] array=s.toCharArray();
            //对称字符字串长度为数的情况
            for(int i=1;i<s.length()-1;i++){
                int from=i;
                int to=i;
            //    要保证不超过字符数组边界的情况下,待扩展的两字符相等
                while(from>=0&&to<s.length()&&array[from]==array[to]){
                    from--;
                    to++;
                }
                int len=to-from-1;
                if(len>max){
                    start=from+1;
                    end=to-1;
                    max=len;
                }
            }
            //对称字符字串长度为偶数的情况
            for(int i=0;i<s.length()-1;i++){
                if(array[i]!=array[i+1])
                    continue;
                int from=i;
                int to=i+1;
                while(from>=0&&to<s.length()&&array[from]==array[to]){
                    from--;
                    to++;
                }
                int len=to-from-1;
                if(len>max){
                    start=from+1;
                    end=to-1;
                    max=len;
                }
            }
            return s.substring(start,end+1);
        }
    }
  • 相关阅读:
    子网掩码的作用与IP网段的划分
    DHCP服务器
    Anaconda安装、更新第三方包
    time模块的使用
    TensorFlow安装
    机器学习-线性回归
    机器学习
    Pyhton-类(2)
    python-类(1)
    Python-函数
  • 原文地址:https://www.cnblogs.com/godlei/p/5568378.html
Copyright © 2011-2022 走看看