时间限制: 2 Sec 内存限制: 256 MB
[提交] [状态]
题目描述
Snuke is interested in strings that satisfy the following conditions:
The length of the string is at least N.
The first N characters equal to the string s.
The last N characters equal to the string t.
Find the length of the shortest string that satisfies the conditions.
Constraints
1≤N≤100
The lengths of s and t are both N.
s and t consist of lowercase English letters.
输入
The input is given from Standard Input in the following format:
N
s
t
输出
Print the length of the shortest string that satisfies the conditions.
样例输入 Copy
3
abc
cde
样例输出 Copy
5
提示
The shortest string is ‘abcde’.
又一个用栈解决的问题。。。
有了昨晚签到题的经验,今晚的签到题猜测可能会考查栈,结果还真是这样(从[状态]一栏中可以看出这些题应该是去年备战比赛的选手们做的)。
题目大意是求满足前n个字符为s且后n个字符为t的字符串的最小长度。考虑到串s的后一部分可能与串t的前一部分相同,可以从串s入手,如果串s的字符与串t的第一个字符相同,就压栈,如果相同,串t的下标j(从0开始)后移一位,直到遍历完串s为止。这时栈中的字符就是串s中与串t中重合的字符之外的部分,栈中的元素个数加上串t的长度就是答案。
举个例子:
s:abcde
t:cdefg
串s和串t中重合的部分为cde.预期结果为abcdefg,答案为7
遍历串s,a,b!=t[0]=c,进栈。
c==t[0]=c,j=j+1=0+1=1.
d==t[1]=d,j=j+1=1+1=2.
e==t[2]=e,j=j+1=2+1=3.
串s遍历结束,栈中元素为a,b,栈大小为2,串t长度为5,二者相加正好等于7
补充一句,还可以求串s和串t中重合部分的长度,即j的值
#include<cstdio>
#include<stack>
using namespace std;
stack<char>pre;
char s[105];
char t[105];
int main()
{
int n,i,j=0;
scanf("%d",&n);
scanf("%s%s",s,t);
for(i=0;i<=n-1;i++)
{
if(s[i]!=t[j])pre.push(s[i]);
else j++;
}
printf("%d",pre.size()+n);
return 0;
}
/**************************************************************
Language: C++
Result: 正确
Time:1 ms
Memory:1944 kb
****************************************************************/