Alien And Password
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
Alien Fred wants to destroy the Earth, but he forgot the password that activates the planet destroyer.
You are given a string S. Fred remembers that the correct password can be obtained from S by erasing exactly one character.
Write a program to calculate the number of different passwords Fred needs to try.
0)
"A"
Answer: 1
In this case, the only password Fred needs to try is an empty string.
1)
"ABA"
Answer: 3
The following three passwords are possible in this case: "BA", "AA", "AB".
2)
"AABACCCCABAA"
Answer: 7
3)
"ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
Answer: 1
Regardless of which character we erase, we will always obtain the same string. Thus there is only one possible password: the string that consists of 49 'Z's.
Output:
For each case,output the answer of the problem.
Sample Input:
A
ABA
AABACCCCABAA
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
Sample Output:
1
3
7
1
解题思路:使用string.erase(pos,num),删除从pos索引开始的num个字符, 返回*this,为了不改变目标字符串str,所以用临时的字符串obj保存删除str中每个位置上的字符前的字符串str,这样每次删除后都将其放在容器set中,最后输出容器中元素的个数即可,水过!
AC代码:
1 #include<bits/stdc++.h>
2 using namespace std;
3 int main(){
4 string str,obj;set<string> st;
5 while(cin>>str){
6 st.clear();//清空
7 for(size_t i=0;i<str.length();++i){
8 obj=str;st.insert(obj.erase(i,1));
9 }
10 cout<<st.size()<<endl;
11 }
12 return 0;
13 }