A string of lowercase letters is called alphabetical if deleting zero or more of its letters can result in
the alphabet string “abcdefghijklmnopqrstuvwxyz”.
Given a string s, determine the minimum number of letters to insert anywhere in the string to
make it alphabetical.
Input
The input consists of a single line containing the string s (1 ≤ |s| ≤ 50).
It is guaranteed that s consists of lowercase ASCII letters ‘a’ to ‘z’ only.
Output
Print, on a single line, a single integer indicating the minimum number of letters that must be
inserted in order to make the string s alphabetical.
Sample Input | Sample Output |
---|---|
xyzabcdefghijklmnopqrstuvw | 3 |
Sample Input | Sample Output |
---|---|
aiemckgobjfndlhp | 20 |
题目大意:给出一个只用小写字母的字符串,求出想字符串中插入最少的字符后能让字符串中出现 “abcdefghijklmnopqrstuvwxyz”.
解题思路:
在26个连续的字母序列中ascll值是从97按照梯度为1逐渐递增,所以这道题其实是求出字符串的ascll值得最长上升子序列。
// Alphabet.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[52],len[52];//储存字符串的ascll值和最长上升子序列
string str;
getline(cin, str);//输入字符串
for (int i = 0; str[i]; i++)//将字符串的ascll赋给a数组
{
a[i] = str[i];
len[i] = 1; //先初始化最长上升子序列的长度为1;
}
string::size_type lenght = str.size();//字符串的长度
//按照动态规划的思想求出最长上升子序列
for (int i = 0; i < lenght; i++)
{
for (int j = 0; j < i; j++)
{
if (a[i] > a[j])
len[i] = max(len[i], len[j] + 1);
}
}
int Max = 0;//找出上升子序列的最长长度
for (int i = 0; i < lenght; i++)
{
if (Max < len[i])
Max = len[i];
}
cout << 26 - Max << endl;
}