NadezhdaGeorgieva

Mirror Words 90/100

Dec 8th, 2020 (edited)
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. package bg.softuni.javafundamentals;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.Map;
  5. import java.util.Scanner;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8.  
  9. public class Fin02_20Apr_MirrorWords {
  10.     public static void main(String[] args) {
  11.         Scanner scanner = new Scanner(System.in);
  12.  
  13.         String text = scanner.nextLine();
  14.         Pattern hiddenWordPattern = Pattern.compile("(@|#)(?<word>[A-Za-z]{3,})\\1\\1(?<mirror>[A-Za-z]{3,})\\1");
  15.         Matcher matcher = hiddenWordPattern.matcher(text);
  16.  
  17.         int wordPairsCount = 0;
  18.         Map<String, String> mirrorPairs = new LinkedHashMap<>();
  19.         while (matcher.find()){
  20.             wordPairsCount++;
  21.             String firstWord = matcher.group("word");
  22.             String secondWord = new StringBuilder(matcher.group("mirror")).reverse().toString();
  23.             if (firstWord.equals(secondWord)){
  24.                 mirrorPairs.put(firstWord, matcher.group("mirror"));
  25.             }
  26.         }
  27.         if (wordPairsCount == 0){
  28.             System.out.println("No word pairs found!");
  29.         } else {
  30.             System.out.printf("%d word pairs found!%n", wordPairsCount);
  31.         }
  32.  
  33.         if (mirrorPairs.isEmpty()) {
  34.             System.out.println("No mirror words!");
  35.         }else {
  36.             System.out.println("The mirror words are:");
  37.             int count = 0;
  38.             for (Map.Entry<String, String> entry : mirrorPairs.entrySet()) {
  39.                 System.out.printf("%s <=> %s", entry.getKey(), entry.getValue());
  40.                 if (count < mirrorPairs.size() - 1){
  41.                     System.out.print(", ");
  42.                 }
  43.                 count++;
  44.             }
  45.         }
  46.     }
  47. }
  48.  
Add Comment
Please, Sign In to add comment