Advertisement
dimipan80

Java Regex: Valid Usernames

Aug 4th, 2017
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.41 KB | None | 0 0
  1. /*
  2.  * You are part of the back-end development team of the next Facebook.
  3.  * You are given a line of usernames, between one of the following symbols: space, “/”, “\”, “(“, “)”.
  4.  * First you have to export all valid usernames. A valid username starts with a letter and can contain only letters, digits and “_”.
  5.  * It cannot be less than 3 or more than 25 symbols long.
  6.  * Your task is to sum the length of every 2 consecutive valid usernames and print on the console
  7.  *   the 2 valid usernames with biggest sum of their lengths, each on a separate line.
  8.  *
  9.  * The Input comes from the console. One line will hold all the data. The line will hold characters in the range [0 … 9999].
  10.  * It will hold usernames, divided by the symbols: space, “/”, “\”, “(“, “)”.
  11.  * The input data will always be valid and in the format described. There is no need to check it explicitly.
  12.  *
  13.  * Print at the console the 2 consecutive valid usernames with the biggest sum of their lengths each on a separate line.
  14.  * If there are 2 or more couples of usernames with the same sum of their lengths, print he left most.
  15.  */
  16.  
  17.  
  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStreamReader;
  21. import java.util.ArrayList;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24.  
  25. public class ValidUsernames {
  26.     public static void main(String[] args) throws IOException {
  27.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  28.         String[] usernames = reader.readLine().split("[\\s()/\\\\]+");
  29.  
  30.         ArrayList<String> validNames = new ArrayList<>(usernames.length);
  31.  
  32.         Pattern pattern = Pattern.compile("\\b[a-zA-Z]\\w{2,24}\\b");
  33.         Matcher matcher;
  34.         for (String username : usernames) {
  35.             matcher = pattern.matcher(username);
  36.             if (matcher.find()) {
  37.                 validNames.add(username);
  38.             }
  39.         }
  40.  
  41.         int maxSum = 0;
  42.         int indexSecondName = 1;
  43.         for (int i = 1; i < validNames.size(); i++) {
  44.             int currentSum = validNames.get(i).length() + validNames.get(i - 1).length();
  45.             if (currentSum > maxSum) {
  46.                 maxSum = currentSum;
  47.                 indexSecondName = i;
  48.             }
  49.         }
  50.  
  51.         System.out.println(validNames.get(indexSecondName - 1));
  52.         System.out.println(validNames.get(indexSecondName));
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement