1. 程式人生 > >2017騰訊校招暑期實習生筆試題1

2017騰訊校招暑期實習生筆試題1

構造迴文

給定一個字串s,你可以從中刪除一些字元,使得剩下的串是一個迴文串。如何刪除才能使得迴文串最長呢?
輸出需要刪除的字元個數。

輸入描述:

輸入資料有多組,每組包含一個字串s,且保證:1<=s.length<=1000.

輸出描述:

對於每組資料,輸出一個整數,代表最少需要刪除的字元個數。

示例1

輸入

abcda
google

輸出

2
2

解題思路:

            找到兩個字串最大的公共子串即可

 程式碼:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int temp[1001][1001];

/*****************
  * 樣例:
  * google
  * elgoog
  * 解題思路:
  * 新建一個字串,將其倒置,可將子看成二維字元陣列
  * 找到兩個字串最大的公共子串即可
*****************/
int calNum(std::string & str)
{
	::memset(temp,0,sizeof(temp));
	std::string str1(str);

	//倒置字串
	::reverse(str1.begin(),str1.end());
	int len = str.length();
	for (int i=0;i<=len-1;i++)
	{
		for (int j=0;j<=len-1;j++)
		{
			if (str[i]==str1[j])
			{
				temp[i + 1][j + 1] = temp[i][j] + 1;
			}
			else
			{
				temp[i + 1][j + 1] = ::max(temp[i + 1][j], temp[i][j + 1]);
			}
		}
	}

	return len - temp[len][len];
}


int main()
{
	int n;
	std::string str;

	while (std::cin >> str)
	{
		std::cout << calNum(str) << std::endl;
	}

	getchar(); getchar();
	return 0;
}