一道字符串题——对substr的使用

You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.

Initially, you have an empty string. Until you type the whole string, you may perform the following operation:

add a character to the end of the string.
Besides, at most once you may perform one additional operation: copy the string and append it to itself.

For example, if you have to type string abcabca, you can type it in 7 operations if you type all the characters one by one. However, you can type it in 5 operations if you type the string abc first and then copy it and type the last character.

If you have to type string aaaaaaaaa, the best option is to type 4 characters one by one, then copy the string, and then type the remaining character.

Print the minimum number of operations you need to type the given string.

Input
The first line of the input containing only one integer number n (1 ≤ n ≤ 100) — the length of the string you have to type. The second line containing the string s consisting of n lowercase Latin letters.

Output
Print one integer number — the minimum number of operations you need to type the given string.

Examples
Input
7
abcabca
Output
5
Input
8
abcdefgh
Output
8
Note
The first test described in the problem statement.

In the second test you can only type all the characters one by one.

题目链接

https://vjudge.net/contest/280107#problem/A

扫描二维码关注公众号,回复: 5080428 查看本文章

题目大意

输入n表示输入一串长度为n的字符串,要复制这一段字符串分两种情况

  1. 一个一个复制单个字符,直到复制完为止。答案为N。
  2. 可以执行一次复制前面已经添加的字符,把复制的添加到后面,然后继续添加字符,直到添加完。答案为N - 复制长度 + 1。
    问最少需要几步就可以完成复制。

数据范围

n (1 ≤ n ≤ 100)

解题思路

用cnt来记字符串第1个字符到往后i个字符和第i个字符再往后i个字符相同时的长度。i得到最长的情况就找到了最少次数。
substr用法: s.substr(i,j)表示从下标为i的位置开始截取j位。

解决代码

#include<cstdio>
#include<algorithm>
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
int main()
{
int n,cnt = 1;
string s;
scanf("%d",&n);
cin>>s;
for(int i=1; i<=n; i++){
    if(s.substr(0,i)==s.substr(i,i))  cnt = i;
}
printf("%d\n",n - cnt + 1);
return 0;
}

猜你喜欢

转载自blog.csdn.net/FOWng_lp/article/details/86656445