面向对象程序设计JAVA学习记录(6)

1.Use the Singleton Design Pattern

Objective

In this exercise you will modify the Bank class to implement the Singleton design pattern.

Directions

Start by changing your working directory to exercise1 on your computer(or anywahere else you like). Copy your all of the Java files from previous exercise of the "Class Design" module into the banking.domain package directory.

Note: at this stage the Banking Project has need for a more complex package hierarchy because we will be creating a CustomerReport class which belongs in the banking.reports package. Therefore, the "domain" classes need to be placed in the banking/domain directory. Also, you will need to change the package declaration for each of these files.

Modify the Bank Class to Implement the Singleton Design Pattern

  1. Modify the Bank class to create a public static method, called getBank, that returns an instance of the Bank class.

  2. The single instance should be a static attribute and should be private. Likewise, make the Bank constructor private.

Modify the CustomerReport Class

In the previous Banking Project exercise, the "customer report" was embedded in the main method of the Main program. In this exercise, this code has been pulled out into the CustomerReport class in the banking.reports package. Your task will be to modify this class to use the Singleton bank object. The contents of the class is as follows:

package banking.reports;

import banking.domain.*;
import java.text.NumberFormat;

public class CustomerReport {

public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();

Bank bank = /*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/

Customer customer;

System.out.println("CUSTOMERS REPORT");
System.out.println("================");

for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);

System.out.println();
System.out.println("Customer: "
+ customer.getLastName() + ", "
+ customer.getFirstName());

for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";

// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}

// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+ currency_format.format(account.getBalance()));
}
}
}

}

要求对输出的语句做一个封装

前置代码

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.text.NumberFormat;
import java.util.*;
class Main {
	public static void main(String[] args) {
		Bank bank = Bank.getBank();
		Customer customer;
		int curCustomer = 0;
		Scanner s = new Scanner(System.in);
		int t = s.nextInt();
		s.nextLine();
		// Create several customers and their accounts according to data
		while (t-- > 0) {
			String f = s.next();
			String l = s.next();
			s.nextLine();
			bank.addCustomer(f, l);
			customer = bank.getCustomer(curCustomer++);
			int numAccount = s.nextInt();
			s.nextLine();
			while (numAccount-- > 0) {
				String[] type = s.nextLine().split(" ");
				double balance;
				double interesOrProtect;
				char op = type[0].charAt(0);
				if (op == 'C' || op == 'c') {
					balance = Double.parseDouble(type[1]);
					if (type.length == 3) {
						interesOrProtect = Double.parseDouble(type[2]);
						customer.addAccount(new CheckingAccount(balance,
								interesOrProtect));
					} else {
						customer.addAccount(new CheckingAccount(balance));
					}
				} else if (op == 'S' || op == 's') {
					balance = Double.parseDouble(type[1]);
					interesOrProtect = Double.parseDouble(type[2]);
					customer.addAccount(new SavingsAccount(balance,
							interesOrProtect));
				} else if (op == 'A' || op == 'a') {
					int cIndex = Integer.parseInt(type[1]);
					int aIndex = Integer.parseInt(type[2]);
					customer.addAccount(bank.getCustomer(cIndex).getAccount(
							aIndex));
				}
			}
		}
		
		CustomerReport cr = new CustomerReport();
		cr.generateReport();
	}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */
class Account {
  protected double balance;
  public Account(double init_balance) {
    balance = init_balance;
  }
  public double getBalance() {
    return balance;
  }
  public boolean deposit(double amt) {
    balance += amt;
    return true;
  }
  public boolean withdraw(double amt) {
    if (balance >= amt) {
      balance -= amt;
      return true;
    } else
      return false;
  }
}
class SavingsAccount extends Account {
  private double interestRate;
  public SavingsAccount(double balance, double interest_rate) {
    super(balance);
    interestRate = interest_rate;
    this.balance = balance;
  }
}
class CheckingAccount extends Account {
  private Account protectedBy ;
  public CheckingAccount(double init_balance) {
    super(init_balance);
  }
  public CheckingAccount(double init_balance,double interesOrProtect) {
    super(init_balance);
  }
  public boolean withdraw(double amt) {
    if (balance >= amt) {
      balance -= amt;
    } else {
      if (protectedBy != null && protectedBy.getBalance() >= (amt - balance)) {
        protectedBy.withdraw(amt - balance);
        balance = 0;
      } else {
        return false;
      }
    }
    return true;
  }
}
class Bank {
  private Customer[] customers = new Customer[15];
  private int numberOfCustomers;
  private static Bank bank = new Bank();
  public Bank() {
  }
  public static Bank getBank() {
    return bank;
  }
  public void addCustomer(String f, String l) {
    customers[numberOfCustomers] = new Customer(f, l);
    numberOfCustomers++;
  }
  public int getNumOfCustomers() {
    return numberOfCustomers;
  }
  public Customer getCustomer(int index) {
    return customers[index];
  }
}
class Customer {
  private String firstName;
  private String lastName;
  private Account[] accounts;
  private int numberOfAccounts;
  private Account savingsAccount = null;
  private Account checkingAccount = null;
  public Customer(String f, String l) {
    firstName = f;
    lastName = l;
    accounts = new Account[2];
  }
  public String getFirstName() {
    return firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public Account getAccount(int index) {
    return accounts[index];
  }
  public int getNumOfAccounts() {
    return numberOfAccounts;
  }
  public void addAccount(Account account) {
    accounts[numberOfAccounts++] = account;
  }
  public Account getSavings() {
    return savingsAccount;
  }
  public void setSavings(Account savingsAccount) {
    this.savingsAccount = savingsAccount;
  }
  public Account getChecking() {
    return checkingAccount;
  }
  public void setChecking(Account checkingAccount) {
    this.checkingAccount = checkingAccount;
  }
}
class CustomerReport {
  public void generateReport() {
  NumberFormat currency_format = NumberFormat.getCurrencyInstance(Locale.US);
  
  Bank bank = Bank.getBank();/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
  
  Customer customer = null;
  
  System.out.println("CUSTOMERS REPORT");
  System.out.println("================");
  
  for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
  customer = bank.getCustomer(cust_idx);
  
  System.out.println();
  System.out.println("Customer: "+ customer.getLastName() + ", "+ customer.getFirstName());
  
  for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
  Account account = customer.getAccount(acct_idx);
  String account_type = "";
  
  // Determine the account type
  if ( account instanceof SavingsAccount ) {
  account_type = "Savings Account";
  } else if ( account instanceof CheckingAccount ) {
  account_type = "Checking Account";
  } else {
  account_type = "Unknown Account Type";
  }
  
  // Print the current balance of the account
  System.out.println("    " + account_type + ": current balance is "
  + currency_format.format(account.getBalance()));
  }
  }
  }
}

 2.Nearly Lucky Number

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.

Input

There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger.  Each line contains an integer n (1 ≤ n ≤ 1018).

Output

For each test, print T lines of "YES" or "NO". Print "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).

Sample test(s)

input

1
40047

output

NO

input

1
7747774

output

YES

input

1
1000000000000000000

output

NO

Note

In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".

In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".

In the third sample there are no lucky digits, so the answer is "NO".

找到幸运数,字符串长要是4或者7,且里面必须由4或者7构成

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        s.nextLine();
        for(int i = 0; i < n; i++) {
            String str = s.nextLine();
            int len = str.length();
            char[] arr = str.toCharArray();
            int flag = 0;
            for(int j = 0; j < len; j++) {
                if(arr[j] == '4' || arr[j] == '7') {
                    flag ++;
                }
            }
            if(flag == 4 || flag == 7) System.out.println("YES");
            else System.out.println("NO");
        }
        s.close();
    }
}

3.Lucky String(Optional)

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number.

For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are:

  • b: 2
  • c: 3, 10
  • d: 4, 8
  • e: 6
  • f: 7
  • z: 1, 5, 9
  • Lists of positions of letters a, g, h, ..., y are empty.

    This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4.

    Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.

    Find the lexicographically minimal lucky string whose length equals n.

Input

There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger n.

Output

For each test, print T lines of lexicographically minimal lucky string whose length equals n.

Sample test(s)

input

1
5

output

abcda

input

1
3

output

abc

Note

The lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < iaj = bj.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i < n; i++) {
            int len = s.nextInt();
            int a = len/4;
            int b = len%4;
            for(int j = 0; j < a; j++) {
                System.out.printf("abcd");
            }
            if(b == 0) System.out.printf("\n");
            else if(b == 1) System.out.printf("a\n");
            else if(b == 2) System.out.printf("ab\n");
            else if(b == 3) System.out.printf("abc\n");
        }
        s.close();
    }
}

4.Lucky Sum of Digits(Optional)

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

Input

There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger. Each line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.

Output

For each test, print T lines of the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.

Sample test(s)

input

1
11

output

47

input

1
10

output

-1

求最小组成的串,首先考虑由7组成

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        long n = s.nextInt();
        for(long i = 0; i < n; i++) {
            long num = s.nextInt();
            int flag = 0;
            for(int j = 0; j < num/4+1; j++){
                if((num - 4*j)%7 == 0){
                    num = num-4*j;
                    for(int k = 0; k < j; k++){
                        System.out.print("4");
                    }
                    while(num != 0){
                        System.out.print("7");
                        num -= 7;
                    }
                    flag = 1;
                }
            }
            if(flag == 1) System.out.print("\n");
            else System.out.println("-1");
        }
        s.close();
    }
}

5.Spreadsheets

In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.

The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23.

Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.

Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.

Input

The first line of the input contains integer number n (1 ≤ n ≤ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .

Output

Write n lines, each line should contain a cell coordinates in the other numeration system.

Sample test(s)

input

2
R23C55
BC23

output

BC23
R23C55

要可以实现二十六到十的进制转换

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        s.nextLine();
        for(int i = 0; i < n; i++) {
            String str = s.nextLine();
            int len = str.length();
            int j, a, b;
            if(str.charAt(0) == 'R') {
                for(j = 0; j < len; j++) {
                    if(str.charAt(j) == 'C') break;
                }
                String str1 = str.substring(1, j);
                String str2 = str.substring(j + 1, len);
                a = Integer.parseInt(str1);
                b = Integer.parseInt(str2);
                if(b <= 26) System.out.printf("%c%d\n", b+64, a);
                else if(b <= 729) {
                    int p1 = b/26;
                    int p2 = b%26;
                    if(p2 == 0) {
                        p1 -= 1;
                        p2 = 26;
                    }
                    System.out.printf("%c%c%d\n", p1+64, p2+64, a);
                }
                else if(b <= 19682) {
                    int p1 = b/729;
                    int p2 = (b-p1*729)/26;
                    int p3 = (b-p1*729)%26;
                    if(p3 == 0) {
                        p2 -= 1;
                        p3 = 26;
                    }
                    System.out.printf("%c%c%c%d\n", p1+65, p2+64, p3+64, a);
                }
            }
            else {
                int k;
                for(j = 1; j < len; j++) {
                    if(str.charAt(j) <= '9') break;
                }
                String str1 = str.substring(0, j);
                String str2 = str.substring(j);
                int lon = str1.length();
                int num = 0;
                for(k = 0; k < lon; k++) {
                    int temp = (int)(str1.charAt(k)-64);
                    num += temp*Math.pow(26, lon-k-1);
                    System.out.println(temp);
                }
                System.out.println("R" + str2 + "C" + num);
            }
        }
        s.close();
    }
}

6.Winner

The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored m points first. Initially each player has 0 points. It's not guaranteed that at the end of the game at least one player has a positive number of points.

Input

The first line contains an integer number n (1  ≤  n  ≤  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.

Output

Print the name of the winner.

Sample test(s)

input

3
mike 3
andrew 5
mike 2

output

andrew

input

3
andrew 3
andrew 2
mike 5

output

andrew

这里利用了数组的思想,字符串数组记录名字,一个数组记录分数,一个数组记录是哪一步最高分

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        String[] name = new String[n];
        int[] num = new int[n];
        int[] step = new int[n];
        for(int i = 0; i < n; i++) num[i] = 0;
        for(int i = 0; i < n; i++) {
            String str = s.next();
            name[i] = str;
            num[i] = s.nextInt();
            step[i] = i;
            for(int k = 0; k < i; k++) {
                if(name[k].equals(name[i])) {
                    num[k] += num[i];
                    step[i] = -1;
                    step[k] = i;
                }
            }
        }
        int max = num[0];
        int first = step[0];
        String na = name[0];
        for(int i = 0; i < n; i++) {
            if(step[i] == -1) continue;
            if(max < num[i]) {
                max = num[i];
                first = step[i];
                na = name[i];
            }
            else if(num[i] == max && step[i] < first){
                first = step[i];
                na = name[i];
            }
        }
        System.out.println(na);
        s.close();
    }
}

7.Registration system

A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle.

Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1,name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

Input

The first line contains number n (1 ≤ n ≤ 105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.

Output

Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.

Sample test(s)

input

4
abacaba
acaba
abacaba
acab

output

OK
OK
abacaba1
OK

input

6
first
first
second
second
third
third

output

OK
first1
OK
second1
OK
third1

一个字符串数组记录名字,一个数组记录次数

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        s.nextLine();
        String[] name = new String[n];
        int[] num = new int[n];
        for(int i = 0; i < n; i++) num[i] = 0;
        for(int i = 0; i < n; i++) {
            String str = s.nextLine();
            int flag = 0;
            for(int j = 0; j < i; j++) {
                if(str.equals(name[j])) {
                    flag = 1;
                    num[j]++;
                    System.out.println(str + num[j]);
                }
            }
            if(flag == 0) {
                name[i] = str;
                System.out.println("OK");
            }
        }
        s.close();
    }
}

8.Center Alignment

Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.

You are to implement the alignment in the shortest possible time. Good luck!

Input

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Output

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

Sample test(s)

Please refer to the test cases.

测试输入

期待的输出

时间限制

内存限制

额外进程

测试用例 1 以文本方式显示
  1. This  is↵
  2. Codeforces↵
  3. Beta↵
  4. Round↵
  5. 5↵
以文本方式显示
  1. ************↵
  2. * This  is *↵
  3. *          *↵
  4. *Codeforces*↵
  5. *   Beta   *↵
  6. *  Round   *↵
  7. *     5    *↵
  8. ************↵
1秒 无限制 0
测试用例 2 以文本方式显示
  1. welcome to the↵
  2. Codeforces↵
  3. Beta↵
  4. Round 5↵
  5. and↵
  6. good luck↵
以文本方式显示
  1. ****************↵
  2. *welcome to the*↵
  3. *  Codeforces  *↵
  4. *     Beta     *↵
  5. *   Round 5    *↵
  6. *              *↵
  7. *      and     *↵
  8. *  good luck   *↵
  9. ****************↵
1秒

这里可以用一个标记flag=+-1来计算左右交替输出

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        String[] line = new String[1000];
        int[] len = new int[1000];
        int i = 0;
        int max = 0;
        while(s.hasNextLine()) {
            String str = s.nextLine();
            line[i] = str;
            len[i] = str.length();
            if(max < len[i]) max = len[i];
            i++;
        }
        for(int j = 0; j < max + 2; j++) System.out.print("*");
        System.out.println();
        int flag = 1;
        for(int j = 0; j < i; j++) {
            System.out.print("*");
            int a = (max-len[j])/2;
            int b = max - len[j] -a;
            if(a != b) {
                if(flag == -1) {
                    a += 1;
                    b -= 1;
                    flag = 0 - flag;
                }
                else flag = 0 - flag;
            }
            for(int step = 0; step < a; step++) System.out.print(" ");
            System.out.print(line[j]);
            for(int step = 0; step < b; step++) System.out.print(" ");
            System.out.println("*");
        }
        for(int j = 0; j < max + 2; j++) System.out.print("*");
        System.out.println();
        s.close();
    }
}

9.Chat Server's Outgoing Traffic

Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:

  • Include a person to the chat ('Add' command).
  • Remove a person from the chat ('Remove' command).
  • Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).

Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.

Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where lis the length of the message.

As Polycarp has no time, he is asking for your help in solving this problem.

Input

The first line of a test case contains a integer T, indicating there are T lines following, each line is described as following.

There are no more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:

  • +<name> for 'Add' command.
  • -<name> for 'Remove' command.
  • <sender_name>:<message_text> for 'Send' command.

<name> and <sender_name> is a non-empty sequence of Latin letters and digits.<message_text> can contain letters, digits and spaces, but can't start or end with a space.<message_text> can be an empty line.

It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.

All names are case-sensitive.

Output

Print a single number — answer to the problem.

Sample test(s) (Refer to the test cases for the correct spelling of each case)

input

7
+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

output

9

input( the blank here is not correct, take care!)

7
+Mike
-Mike
+Mike
Mike:Hi I am here
-Mike
+Kate
-Kate

output

14

这个问题很简单,不用记录人名,根据-+来计算人数,截取":"后的字符串求长度

import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        s.nextLine();
        int num = 0;
        int len = 0;
        for(int i = 0; i < n; i++) {
            String str = s.nextLine();
            if(str.charAt(0) == '+') num++;
            else if(str.charAt(0) == '-') num--;
            else {
                int j;
                for(j = 0; j < str.length(); j++) {
                    if(str.charAt(j) == ':') break;
                }
                String s1 = str.substring(j + 1);
                len += num*s1.length();
            }
        }
        System.out.println(len);    
        s.close();
    }
}

猜你喜欢

转载自blog.csdn.net/lijj0304/article/details/127435111