TopcoderArchiveVisit Topcoder
Archive
Algorithm problem

Messages

Problem statement, definition, constraints, and public examples.

Problem Statement

Writing small messages on cell phones is very common nowadays. The number of keys on a cell phone is usually quite small, so most phones map several letters to the same key. For instance, the letters 'A', 'B' and 'C' can be mapped to the same key. Pressing that key once will produce the letter 'A', pressing it twice will produce a 'B' and pressing it three times will produce a 'C'. Pressing a key more times than the number of letters mapped to it is only a waste of presses, and will not be considered here.

You have been given the task of analyzing how many key presses are necessary to type a word on a cell phone, given the mapping of letters onto the phone keys.

Create a class Messages which contains the method keyPresses which takes a String word containing the word to be analyzed and a String[] keys containing the mapping of letters onto keys. Each element in keys correspond to a key on the cell phone. The first character in each element in keys requires 1 key press to be produced, the second character requires 2 key presses etc. You may assume each letter 'A'-'Z' occurs exactly once in keys.

Definition

Class:
Messages
Method:
keyPresses
Parameters:
String, String[]
Returns:
int
Method signature:
int keyPresses(String word, String[] keys)
(be sure your method is public)

Constraints

  • word will contain between 1 and 50 characters, inclusive.
  • word will contain only upper case letters, 'A'-'Z'.
  • keys will contain between 1 and 26 elements, inclusive.
  • Each element in keys will contain between 1 and 26 characters, inclusive.
  • Each element in keys will contain only upper case letters, 'A'-'Z'.
  • Each letter 'A'-'Z' will occur exactly once in keys.

Examples

  1. "TOPCODER"
    {"ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"}
    Returns: 17
    The number of keypresses required for each letter in the message are: T = 1, O = 3, P = 1, C = 3, O = 3, D = 1, E = 2, R = 3. This sums up to 1+3+1+3+3+1+2+3=17, so the method should return 17.
  2. "MESSAGE"
    {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
    Returns: 69
    All letters can be mapped to the same key.
  3. "IAMTHEBESTPROGRAMMERINTHEWORLD"
    {"ZKEHL","AJRWP","QIX","MBGUCV","TFYOD","NS"}
    Returns: 79
    The mapped letters don't have to be in lexicographical order.
Back to all problems