Advertisement
NadezhdaGeorgieva

02 Mirror words 100 / 100

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