Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class MirrorWords {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String text = scanner.nextLine();
- // String regex = "([@#])(?<firstWord>[A-z]{3,})\\1{2}(?<secondWord>[A-z]{3,})";
- String regex = "([@#])(?<firstWord>[A-z]{3,})\\1{2}(?<secondWord>[A-z]{3,})[#@]";
- List<String> mirrorWords = new ArrayList<>();
- Pattern pattern = Pattern.compile(regex);
- Matcher matcher = pattern.matcher(text);
- int counter = 0;
- while (matcher.find()) {
- String firstWord = matcher.group("firstWord");
- String secondWord = matcher.group("secondWord");
- counter++;
- StringBuilder reversedWord = new StringBuilder(secondWord);
- reversedWord.reverse();
- if (firstWord.equals(reversedWord.toString())) {
- mirrorWords.add(firstWord + " <=> " + secondWord);
- }
- }
- if (counter != 0) {
- System.out.printf("%d word pairs found!%n", counter);
- } else {
- System.out.println("No word pairs found!");
- }
- if (counter > 0 && mirrorWords.size() > 0) {
- System.out.println("The mirror words are:");
- System.out.print(String.join(", ", mirrorWords));
- } else {
- System.out.println("No mirror words!");
- }
- }
- }
Add Comment
Please, Sign In to add comment