Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package bg.softuni.javafundamentals;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class Fin02_20Apr_MirrorWords {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String text = scanner.nextLine();
- Pattern hiddenWordPattern = Pattern.compile("(@|#)(?<word>[A-Za-z]{3,})\\1\\1(?<mirror>[A-Za-z]{3,})\\1");
- Matcher matcher = hiddenWordPattern.matcher(text);
- int wordPairsCount = 0;
- Map<String, String> mirrorPairs = new LinkedHashMap<>();
- while (matcher.find()){
- wordPairsCount++;
- String firstWord = matcher.group("word");
- String secondWord = new StringBuilder(matcher.group("mirror")).reverse().toString();
- if (firstWord.equals(secondWord)){
- mirrorPairs.put(firstWord, matcher.group("mirror"));
- }
- }
- if (wordPairsCount == 0){
- System.out.println("No word pairs found!");
- } else {
- System.out.printf("%d word pairs found!%n", wordPairsCount);
- }
- if (mirrorPairs.isEmpty()) {
- System.out.println("No mirror words!");
- }else {
- System.out.println("The mirror words are:");
- int count = 0;
- for (Map.Entry<String, String> entry : mirrorPairs.entrySet()) {
- System.out.printf("%s <=> %s", entry.getKey(), entry.getValue());
- if (count < mirrorPairs.size() - 1){
- System.out.print(", ");
- }
- count++;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment