练习cf1547BB. Alphabetical Strings
题目如下
B. Alphabetical Strings
time limit per test2 seconds
memory limit per test512 megabytes
A string 𝑠 of length 𝑛 (1≤𝑛≤26) is called alphabetical if it can be obtained using the following algorithm:
first, write an empty string to 𝑠 (i.e. perform the assignment 𝑠 := "");
then perform the next step 𝑛 times;
at the 𝑖-th step take 𝑖-th lowercase letter of the Latin alphabet and write it either to the left of the string 𝑠 or to the right of the string 𝑠 (i.e. perform the assignment 𝑠 := 𝑐+𝑠 or 𝑠 := 𝑠+𝑐, where 𝑐 is the 𝑖-th letter of the Latin alphabet).
In other words, iterate over the 𝑛 first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string 𝑠 or append a letter to the right of the string 𝑠. Strings that can be obtained in that way are alphabetical.
For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".
From the given string, determine if it is alphabetical.
Input
The first line contains one integer 𝑡 (1≤𝑡≤104) — the number of test cases. Then 𝑡 test cases follow.
Each test case is written on a separate line that contains one string 𝑠. String 𝑠 consists of lowercase letters of the Latin alphabet and has a length between 1 and 26, inclusive.
Output
Output 𝑡 lines, each of them must contain the answer to the corresponding test case. Output YES if the given string 𝑠 is alphabetical and NO otherwise.
You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive answer).
题目大意
现规定字符串,按照字母表的顺序特殊排列,从首字母a开始,依次添加每次添加在当前字符串的左边或右边,判断下列字符串是否符合规则。
题目分析
要求按照字母表顺序特殊排列,那么首先检查是否有‘a';
点击查看代码
int alp = 0;
if(find(s.begin(),s.end(),'a') != s.end()){
alp = 1;
}
点击查看代码
bool check(string s){
int len = s.size();
int pos = s.find('a');
int l = pos - 1, r = pos + 1;
char next = 'b';
while(next < 'a' + len){
if(s[l] == next){
l--;
next++; //查找字母表中下一字母
}else if(r < len && s[r] == next){
r++;
next++; //查找字母表中下一字母
}else{
return false;
}
}
return true;
}
完整代码
点击查看代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool check(string s){
int len = s.size();
int pos = s.find('a');
int l = pos - 1, r = pos + 1;
char next = 'b';
while(next < 'a' + len){
if(s[l] == next){
l--;
next++; //查找字母表中下一字母
}else if(r < len && s[r] == next){
r++;
next++; //查找字母表中下一字母
}else{
return false;
}
}
return true;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
string s;
cin >> s;
int alp = 0;
if(find(s.begin(),s.end(),'a') != s.end()){
alp = 1;
}
if(alp && check(s)){
printf("Yes\n");
}else{
printf("No\n");
}
}
}

浙公网安备 33010602011771号