SRM257(1):SubstitutionCode

来源:互联网 发布:ubuntu怎么安装依赖项 编辑:程序博客网 时间:2024/05/22 16:52

Problem Statement

     A simple, easy to remember system for encoding integer amounts can be very useful. For example, dealers at flea markets put the information about an item on a card that they let potential buyers see. They find it advantageous to encode the amount they originally paid for the item on the card.

A good system is to use a substitution code, in which each digit is encoded by a letter. An easy to remember 10-letter word or phrase, the key, is chosen. Every '1' in the value is replaced by the first letter of the key, every '2' is replaced by the second letter of the key, and so on. Every '0' is replaced by the last letter of the key. Letters that do not appear in the key can be inserted anywhere without affecting the value represented by the code.. This helps to make the resulting code much harder to break (without knowing the key).

Create a class SubstitutionCode that contains the method getValue that is given the Strings key and code as input and that returns the decoded value.

 

Definition

     Class: SubstitutionCode Method: getValue Parameters: String, String Returns: int Method signature: int getValue(String key, String code) (be sure your methodis public)       

Constraints

- code contains between 1 and 9 characters inclusive, all uppercase letters 'A'-'Z' - code contains at least one letter that is found in key - key contains exactly 10 uppercase letters 'A'-'Z', all distinct from each other  

Examples

0)     
"TRADINGFEW"
"LGXWEV"
Returns: 709
The L,X, and V are ignored since they do not appear in the key. G is the seventh letter in the key, W is the 10th letter, and E is the 9th letter. 1)     
"ABCDEFGHIJ"
"XJ"
Returns: 0
2)     
"CRYSTALBUM"
"MMA"
Returns: 6

My Solution:

(ccnupq  2006-04-19  http://blog.csdn.net/ccnupq/)

#include <iostream>
#include <string>

using namespace std;

class SubstitutionCode
{
public:
    int getValue(string key, string code);
};

int SubstitutionCode::getValue(string key, string code)
{
    int i,pos=-1,num=0;
    if(key.length()!=10)
         return -1;
    for(i=0;i<=code.length();i++)
    {
        pos=key.find(code[i]);
        if(pos==string::npos)
            continue;
        if(pos==9) 
            num=num*10;
        else
        {
            pos++;
            num=num*10+pos;
        }
    }  
    return num;

}
 
int main()
{
    SubstitutionCode SubstitutionCodeObj;
    int num=-1;
    string key="CRYSTALBUM";
    string code="MMA";
    num=SubstitutionCodeObj.getValue(key,code);
    cout<<num;
    return 0;
}

原创粉丝点击