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

    玩了两天dota2,罪过罪过,还是应该老老实实刷题啊。

    题目求得是最长的回文子串,这里使用的是暴力的解法,也就是解决两种回文"asdsa"以及"assa",即奇数以及偶数回文,相当于用了二重循环,代码如下:

     1 class Solution {
     2 public:
     3     string longestPalindrome(string s) {
     4         if (!s.size()) return "";
     5         string ret;
     6         string tmp;
     7         for (int i = 0; i < s.size(); ++i){
     8             tmp = findPal(s, i - 1, i + 1);
     9             if (tmp.size() > ret.size())
    10                 ret = tmp;
    11             tmp = findPal(s, i , i + 1);
    12             if (tmp.size() > ret.size())
    13                 ret = tmp;
    14         }
    15         return ret;
    16     }
    17     
    18     string findPal(string & s,  int left, int right)
    19     {
    20         if (left < 0)
    21             return s.substr(left + 1, 1);
    22         if (right >= s.size())
    23             return s.substr(right - 1, 1);
    24 
    25         while (left >= 0 && right < s.size()){
    26             if (s[left] != s[right])
    27                 break;
    28             left--;
    29             right++;
    30         }
    31         left++;
    32         return s.substr(left, right - left);
    33     }
    34 };
  • 相关阅读:
    Elasticsearch的RESTful API使用
    Elasticsearch简介与安装
    安装MySQL
    数据处理与文件查找,压缩与解压
    Linux网络设置
    文件与文件夹
    基本命令
    se
    爬虫请求库之requests
    redis五种数据类型
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4928920.html
Copyright © 2011-2022 走看看