zoukankan      html  css  js  c++  java
  • 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 1:

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

    Example 2:

    Input: "cbbd"
    Output: "bb"

    AC code:

    class Solution {
    public:
        string longestPalindrome(string s) {
            int max_left, left, right, max_len, i;
            max_left = 0;
            max_len = 1;
            for (i = 0; i < s.length()-1 && s.length()-i > max_len/2; ) {
                left = right = i;
                while (right < s.length()-1 && s[right] == s[right+1]) 
                    right++;
                i = right+1;
                while (right < s.length()-1 && left > 0 && s[right+1] == s[left-1]) {
                    right++;
                    left--;
                }
                if (max_len <= right-left+1) {
                    max_left = left;
                    max_len = right-left+1;
                }
            }
            return s.substr(max_left, max_len);
        }
    };

    std::string::substr

    string substr (size_t pos = 0, size_t len = npos) const;
    Generate substring

    Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

    The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).

    Parameters

    pos
    Position of the first character to be copied as a substring.
    If this is equal to the string length, the function returns an empty string.
    If this is greater than the string length, it throws out_of_range.
    Note: The first character is denoted by a value of 0 (not 1).
    len
    Number of characters to include in the substring (if the string is shorter, as many characters as possible are used).
    A value of string::npos indicates all characters until the end of the string.


    size_t is an unsigned integral type (the same as member type string::size_type). 

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Eclipse启动不了
    第三章Hibernate关联映射
    System Generator简介
    Chipscope使用
    总线及数据传输技术【待完善】
    多相滤波器
    notepad++与ISE/Vivado关联
    常用IP核
    〖Linux〗Qt+gsoap开发客户端程序,服务端地址设定的字符串转换处理
    〖Android〗OK6410a的Android HAL层代码编写笔记
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9716049.html
Copyright © 2011-2022 走看看