现在的位置: 首页 > 综合 > 正文

Hackerrank Palindrome Index

2018年02月20日 ⁄ 综合 ⁄ 共 781字 ⁄ 字号 评论关闭

先上超时的代码。。。。。。。。。。。自己的 

#include <iostream>
#include <string>

using namespace std ;
bool huiwen( string s )
{
	int len = s.size();
	bool flag =  true;
	for ( int i = 0 ; i < len/2; ++i)
		if (s[i] != s[len-1-i])  flag = false ;
		return flag ;
}
int main()
{
	int t ;
	cin >> t ;
	while(t--)
	{
        
		string s ;
		cin >> s ;
		string res = s ;
		int len = s.size();
		int count = 0 ;
		if ( huiwen(s) )  cout << "-1" << endl;
		else
		{
		
		int i = 0 ;
		while( i != len  )
		{   
			s.erase(i,1);
			if ( huiwen(s)) 
			{
				cout << i << endl ;
				++i;
				s = res;
			}
			else 
			{
				++i;
				++count;
				s = res ;
			}
		}	    
		if(count == len ) cout << "-1" << endl ;
	   }
	}
	return 0 ;
}

下面的没有超时 ,不过不是自己写的 这个人的想法好简洁。。。

#include <iostream>
#include <string>
using namespace std;
 
int main() {
    int T;
    cin >> T;
    while (T--) {
        string s;
        cin >> s;
        int l = 0;
        int r = s.size() - 1;
        while (l < r && s[l] == s[r]) {
            l++;
            r--;
        }
        if (l >= r) {
            cout << -1 << endl;
            continue;
        }
        int ll = l + 1;
        int rr = r;
        while (ll < rr && s[ll] == s[rr]) {
            ll++;
            rr--;
        }
        if (ll >= rr) {
            cout << l << endl;
        } else {
            cout << r << endl;
        }
    }
    return 0;
}

抱歉!评论已关闭.