L2-008 最长对称字串 以下标i展开

来源:互联网 发布:jira ubuntu 破解版 编辑:程序博客网 时间:2024/05/21 14:58

L2-008. 最长对称子串

时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定"Is PAT&TAP symmetric?",最长对称子串为"s PAT&TAP s",于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:
Is PAT&TAP symmetric?
输出样例:
11


以i下标为遍历字符串的坐标,左右展开,j为当前遍历的长度。

每次从i开始,要依次判断奇数偶数的情况,取最大值,注意偶数的时候以左边为基准和以右边为基准都可以,关键要在比较的时候控制好。

还有注意左边界是0,右边界是len-1,所以到len就要break

时间复杂度为O(n*2)级,比我开始无脑用Java写的n*3还是好多了,而且n*3会超时。。。

还有一个回文串算法也可以解决。。

#include <bits/stdc++.h>#define INF 0x3fffffff#define eps 1e-8typedef long long LL;const double pi = acos(-1.0);const int mod = 1e9 + 7;const int maxn = 70;using namespace std;int main() {    string str;    getline(cin,str);    int len = str.length();    int Max = -1;    for(int i = 0; i < len; i++) {            //奇数情况            int ans = 1;        for(int j = 1; j < len; j++) {            if(i-j<0 || i-j >= len || str[i-j]!= str[i+j])                break;//跳到下一个下标            ans+=2;        }        //每一次下标都取一次最值        Max = Max<ans?ans:Max;        //偶数情况        ans = 0;        for(int j = 1; j < len; j++) {//                if(i-j+1<0 || i+j>=len ||str[i+1-j] != str[i+j])//偶数以对称点左边的数为基准                  if(i-j<0 || i-1+j>=len ||str[i-j] != str[i-1+j])//偶数以对称点右边的数为基准                    break;                ans+=2;        }        Max = Max<ans?ans:Max;    }    cout<<Max<<endl;    return 0;}


超时Java,随便伸手写的

import java.util.Scanner;class Main {  public static void main(String[] args) {Scanner sc = new Scanner(System.in);String str = new String();str = sc.nextLine();int sum = 0;int Max = -1;for(int i = 0; i < str.length(); i++)for(int j = str.length() - 1; j >= 0&&j >= i; j-- ) {if(str.charAt(i) == str.charAt(j)){while(i!=j&&j>=i) {sum++;i++;j--;if(str.charAt(i) == str.charAt(j)&&j>i)continue;else {if(sum > Max) {Max = sum;sum = 0;break;}}}}}if(Max == 1)System.out.println(1);elseSystem.out.println(Max*2+1);  }}



0 0
原创粉丝点击