zoukankan      html  css  js  c++  java
  • L2008 最长对称子串

    L2-008 最长对称子串 (25 分)


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


    输入格式

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


    输出格式

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


    输入样例

    Is PAT&TAP symmetric?
    

    输出样例

    11
    

    作者:陈越
    单位:浙江大学
    代码长度限制:16 KB
    时间限制:200 ms
    内存限制:64 MB



    PZ's Solution

    1. 考虑到字符串的长度最大为\(1000\),使用\(O(n^2)\)算法即可;

    2.遍历字符串,以遍历到的某个字符s作为中间点,则有两种情况:

    1).回文字符串长度为奇数,则当前字符为确定的中间点,往两边循环更新回文最大长度;

    2).回文字符串长度为偶数,则当前字符和下一位字符为一个中心,往两边循环更新回文最大长度;


    PZ.cpp

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    string s;
    int ans;
    int main(){
    	getline(cin,s);
    	for(int i=0;i<s.size();++i){
    		int l=i,r=i,res1=-1,res2=0;
    		while(l>=0 && r<s.size() && s[l--]==s[r++]) res1+=2;
    		l=i,r=i+1;
    		while(l>=0 && r<s.size() && s[l--]==s[r++]) res2+=2;
    		ans=max(ans,max(res1,res2));
    	}
    	printf("%d",ans);
    	return 0;
    }
    
  • 相关阅读:
    1058 A+B in Hogwarts (20)
    1036. Boys vs Girls (25)
    1035 Password (20)
    1027 Colors in Mars (20)
    1009. Product of Polynomials (25)
    1006. Sign In and Sign Out
    1005 Spell It Right (20)
    1046 Shortest Distance (20)
    ViewPager页面滑动,滑动到最后一页,再往后滑动则执行一个事件
    IIS7.0上传文件限制的解决方法
  • 原文地址:https://www.cnblogs.com/Potrem/p/L2_008.html
Copyright © 2011-2022 走看看