TOJ 2749 Absent Substrings

描述

Given a string of symbols, it’s natural to look it over and see what substrings are present. In this problem, you are given a string and asked to consider what substrings are absent. Of course, a given string has finite length and therefore only finitely many substrings, so there are always infinitely many strings that don’t appear as substrings of a given string. We’ll seek to find the lexicographically least string that is absent from the given string.

输入

Each line of input contains a string x over the alphabet {a, b, c}. x may be the empty string, as shown in the second line of the input sample below, or a nonempty string. The number of characters in the string x is no more than 250.

输出

For each input string x, find and output the lexicographically least string s over the alphabet {a, b, c} such that s is not a substring of x; i.e. s is absent from x. Since the empty string is a substring of every string, your output s is necessarily nonempty. Recall that a string is lexicographically less than another string if it is shorter or is the same length and alphabetically less; e.g. b

样例输入

bcabacbaa

aaabacbbcacc

样例输出

bb is absent from bcabacbaa
a is absent from 
aac is absent from aaabacbbcacc

题目来源

台州学院第三届大学生程序设计竞赛

 

转换为进制转换的问题。

比如a,b,c,aa,ab,ac,ba...

分别看成1,2,3,4,5,6,7...

从1开始循环,然后使用find函数寻找字符串中是否(含有数字所对应的子串)。

一旦发现没有找到任何的子串就输出,跳出循环。

 

#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

string convertToString(int n){
    string t="",r="";
    while(--n>=0){
        t+=n%3+'a';
        n/=3;
    }
    for(int i=t.size()-1; i>=0;r+=t[i],i--);
    return r;
}

int main()
{
    string str;
    while(getline(cin,str)){
        if(str.size()==0){
            cout<<"a is absent from "<<endl;
            continue;
        }
        int k=1;
        while(1){
            string s=convertToString(k);
            if(str.find(s)==string::npos){
                cout<<s<<" is absent from "<<str<<endl;
                break;
            }
            k++;
        }        
    }    
    return 0;
}

 

你可能感兴趣的:(substring)