最长回文子串

给你一个字符串 s,找到 s 中最长的回文子串。
示例 1:
输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。
示例 2:
输入:s = "cbbd"
输出:"bb"
示例 3:
输入:s = "a"
输出:"a"
示例 4:
输入:s = "ac"
输出:"a"

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/longest-palindromic-substring

解题思路
土味方法,双指针?
中间有一段时间一直在想能不能把一个点和两个点为中心点的方法合起来,可惜太弱了,没想到好方法orz。
继续向大牛们学习,respect!

代码:

class Solution {
    public String longestPalindrome(String s) {
        char[] c1 = s.toCharArray();
        //start和end记录的是最长子串的下标
        int start = 0;
        int end = 0;
        //以一个点为中心点的方式
        for (int i = 1; i<c1.length;i++){
            int s1 = i-1;
            int e1 = i+1;
            while(s1 >= 0 && e1 < c1.length){
                if (c1[s1] == c1[e1]){
                    if (e1-s1>end-start){
                        end = e1;
                        start = s1;
                    }
                    s1--;
                    e1++;
                }else{
                    break;
                }
            }
        }
        //以两个点为中心点的方式
        for (int i = 1; i<c1.length;i++){
            int s1 = i-1;
            int e1 = i;
            while(s1 >= 0 && e1 < c1.length){
                if (c1[s1] == c1[e1]){
                    if (e1-s1>end-start){
                        end = e1;
                        start = s1;
                    }
                    s1--;
                    e1++;
                }else{
                    break;
                }
            }
        }
        String ans = "";
        for (int i=start;i<=end;i++){
            ans += c1[i];
        }
        return ans;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容