Educational Codeforces Round 82 (Rated for Div. 2)C. Perfect Keyboard

C. Perfect Keyboard

题目链接-C. Perfect Keyboard
在这里插入图片描述
在这里插入图片描述
题目大意
输入一个只包含小写字母的字符串,表示按键顺序,键盘只有一行, 问你每次按键能否保证都是按相邻的位置,如果能,输出任意一种键盘的样式,不能则输出NO

解题思路
模拟即可,每添加一个新的字符到序列中时用map记录,若序列中已经存在需要新添加的字符时判断是否符合条件,即判断前一个字母是否在序列的首尾位置即可,最后输出得到的序列

附上代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int INF=0x3f3f3f3f;
const int N=1e5+5;
const int M=1e9+7;
typedef long long ll;
typedef pair<int,int> PII;
signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	
	int t;
	cin>>t;
	while(t--){
		map<char,int> mp;
		string s,str;
		cin>>s;
		str+=s[0];
		mp[s[0]]=1;
		bool flag=0;
		for(int i=1;i<s.length();i++){
			if(mp[s[i]]==0){
				mp[s[i]]++;
				if(str.front()==s[i-1])
					str=s[i]+str;
				else if(str.back()==s[i-1])
					str+=s[i];
				else{
					flag=1;
					break;
				}
			}
			else{
				int k=0;
				for(int j=0;j<str.length();j++){
					if(str[j]==s[i]){
						k=j;
						break;
					}
				}
				if(s[i-1]!=str[k-1]&&s[i-1]!=str[k+1]){
					flag=1;
					break;
				}
			}
		}
		if(flag==1)
			cout<<"NO"<<endl;
		else{
			cout<<"YES"<<endl;
			for(char i='a';i<='z';i++){
				if(mp[i]==0)
					str+=i;
			}
			cout<<str<<endl;
		}
	}
	return 0;
}

发布了78 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/104352293
今日推荐