RGAlex

O2. Mirror Words / FinalExam - O3

Mar 25th, 2021
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package FinalExam.O3;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import java.util.List;
  6. import java.util.Scanner;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9.  
  10. public class O2MirrorWords {
  11.     public static void main(String[] args) {
  12.         Scanner scanner = new Scanner(System.in);
  13.         String input = scanner.nextLine();
  14.         Matcher matcher = Pattern.compile("([@#])(?<first>[A-Za-z]{3,})\\1\\1(?<second>[A-Za-z]{3,})\\1").matcher(input);
  15.  
  16.         int countMatches = 0;
  17.         List<String> mirrorWords = new ArrayList<>();
  18.         while (matcher.find()) {
  19.             countMatches++;
  20.             StringBuilder first = new StringBuilder(String.valueOf(matcher.group("first"))).reverse();
  21.             if (String.valueOf(first).equals(matcher.group("second"))) {
  22.                 mirrorWords.add(String.format("%s <=> %s", matcher.group("first"), matcher.group("second")));
  23.             }
  24.         }
  25.         if (countMatches == 0) {
  26.             System.out.println("No word pairs found!");
  27.         } else {
  28.             System.out.printf("%d word pairs found!%n", countMatches);
  29.         }
  30.         if (mirrorWords.isEmpty()) {
  31.             System.out.println("No mirror words!");
  32.         } else {
  33.             System.out.printf("The mirror words are:%n%s", String.join(", ", mirrorWords));
  34.         }
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment