题目描述
The preferred way to generate user login in Polygon is to concatenate a prefix of the user’s first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).
As a reminder, a prefix of a string ss is its substring which occurs at the beginning of ss : “a”, “ab”, “abc” etc. are prefixes of string “{abcdef}” but “b” and 'bc" are not. A string aa is alphabetically earlier than a string bb , if aa is a prefix of bb , or aa and bb coincide up to some position, and then aa has a letter that is alphabetically earlier than the corresponding letter in bb : “a” and “ab” are alphabetically earlier than “ac” but “b” and “ba” are alphabetically later than “ac”.
输入格式
The input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive.
输出格式
Output a single string — alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.
输入输出样例
输入 #1复制
harry potter
输出 #1复制
hap
输入 #2复制
tom riddle
输出 #2复制
tomr
题意:给定两个用空格分隔的字符串,分别取两字符串的任意非空前缀,将两前缀合并为一个新的字符串,求可行字典序最小的字符串。
题解:一种是贪心,两种字符串都是要取的,那么第一个字符串和第二个字符串的首个字符是一定要取的,因此只是需要判断第一个字符串的剩余字符的字典序与第二个字符串的首字符的关系即可。第二种,由于本题的数据量很小,暴力substr子串截取和拼接是可以解决本题的。
#include <bits/stdc++.h>
#define maxn 10001
using namespace std;
string s,ss;
int main()
{
cin>>s>>ss;
int x=s.length(),y=ss.length();
string s1="zzzzzzzzzzzz";
string s2;
for(int i=0;i<x;i++)//枚举子串
{
for(int j=0;j<y;j++)
{
s2=s.substr(0,i+1)+ss.substr(0,j+1);//把两个字符串枚举的部分拼在一起
s1=min(s1,s2);//比较字典序最小的
}
}
cout<<s1<<endl;
return 0;
}
string.substr()
求子串函数
string str1;
str1.substr(0,1); // 返回str1[0:1] 0位置后的一个字符
str1.substr(2,5); // 返回str1[2:2+5] 2位置后的五个字符
上述的substr函数就是一个拷贝过程,不用考虑时间复杂度。