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.

    Example:

    Input: "babad"
    
    Output: "bab"
    
    Note: "aba" is also a valid answer.

    Example:

    Input: "cbbd"
    
    Output: "bb"


    思路很简单:遍历字符串,找出以每个字符为中间字符的最长的回文串,再次遍历字符,找出以两个重复字符为中间字符的最长的字符串,从而得到字符串 s 的最长回文子串。

    以下是我的代码,其中再确认中间字符时寻找最长回文串的代码重复了两次,也可以独立出一个函数来调用:
    class Solution {
    public:
        string longestPalindrome(string s) {
            int pos = 0, left = 0, right = 0, len = s.size();
            string result = "";
            while (pos < len) {
                while (1) {
                    if (s[left] != s[right]) break;
                    string tmp = s.substr(left, right - left + 1);
                    if (tmp.size() > result.size()) result = tmp;
                    if (--left < 0) break;
                    if (++right >= len) break;
                }
                pos++;
                left = pos, right = pos;
            }
            for (int i = 0; i < len - 1; i++) {
                if (s[i] == s[i+1]) {
                    left = i, right = i+1;
                    while (1) {
                        if (s[left] != s[right]) break;
                        string tmp = s.substr(left, right - left + 1);
                        if (tmp.size() > result.size()) result = tmp;
                        if (--left < 0) break;
                        if (++right >= len) break;
                    }
                }
            }
            return result;
        }
    };



  • 相关阅读:
    element表格添加序号
    ZOJ 3822 Domination(概率dp)
    HDU 3037(Lucas定理)
    HDU 5033 Building(单调栈维护凸包)
    HDU 5037 Frog(贪心)
    HDU 5040 Instrusive(BFS+优先队列)
    HDU 5120 Intersection(几何模板题)
    HDU 5115 Dire Wolf(区间dp)
    HDU 5119 Happy Matt Friends(dp+位运算)
    C++ string详解
  • 原文地址:https://www.cnblogs.com/zmj97/p/7651490.html
Copyright © 2011-2022 走看看