第七周作业2(LeetCode5)

1. 题目描述(LeetCode5)
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

2. 解决思路
因为用string类型定义的字符串可以直接调用函数获得字符串的长度以及可以用数组下标的形式获得对应位置上的单个字符,所以可以不用把字符串再用数组保存(char类型的则不行),而直接对字符串进行相应的函数调用操作。在解题过程中,以每个s[i]字符为中心,两边测试看以这个字符为中心的回文长度是多少,然后再 以每两个字符s[i-1]s[i]为中心,测试这两个字符是否相等,和以这两个字符为中心的回文有多长
最后记录最大长度和最大长度子串起点,调用substr()函数对字符串进行截取操作即可获得最长的回文子串。

3. 完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;



int testTwoSides(string &s, int low, int up)
{
    int n = s.length();
    int max = 0;
    if (low == up)
    {
        low--;
        up++;
        max = 1;
    }
    while (low >= 0 && up < n && s[low] == s[up])
    {
        max += 2;
        low--;
        up++;
    }
    return max;
}

string longestPalindrome(string &s)
{
    int n = s.length();
    int subStartPoint = 0;
    int maxstrlen = 1;
    int temp = 0;
    for (int i = 0; i < n; i++)
    {
        temp = testTwoSides(s, i, i);
        if (temp > maxstrlen)
        {
            subStartPoint = i - temp / 2;
            maxstrlen = temp;
        }
    }
    for (int i = 1; i < n; i++)
    {
        temp = testTwoSides(s, i - 1, i);
        if (temp > maxstrlen)
        {
            subStartPoint = i - temp / 2;
            maxstrlen = temp;
        }
    }
    return s.substr(subStartPoint, maxstrlen);
}

int main()
{
    string s;

    printf("请输入任意字符串:\n");
    cin >> s;
    int low = 0;
    int up = s.length() - 1;
    string result = longestPalindrome(s);
    cout <<"最长的回文字符串是:"<< result << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值